我有一个 List<MyObject>
...
MyObject 有一个名为 LineId(整数)的属性...
所以,我需要将列表中所有连续的 LineId 分开......
示例:
List<MyObject> :
LineId =1
LineId =1
LineId =1
LineId =2
LineId =1
LineId =2
结果必须是 4 个分隔列表:
LineId =1
LineId =1
LineId =1
-------------
LineId =2
-------------
LineId =1
-------------
LineId =2
所以,我必须分开所有连续的 LineId ...
有使用 Linq 的简单方法吗?
谢谢
最佳答案
嗯,我不认为 linq 是解决这个问题的最干净的解决方案。我认为以下代码可能比任何 LINQ 都简单易读得多。
List<MyObject> currentList = new List<MyObject>();
List<List<MyObject>> finalList = new List<List<MyObject>>();
for (int i = 0; i < myObjects.Count; i++)
{
//If the list is empty, or has the same LineId, add to it.
if (currentList.Count == 0 || currentList[0].LineId == myObjects[i].LineId)
{
currentList.Add(myObjects[i]);
}
//Otherwise, create a new list.
else
{
finalList.Add(currentList);
currentList = new List<MyObject>();
currentList.Add(myObjects[i]);
}
}
finalList.Add(currentList);
我知道您要求使用 linq,但我认为这可能是更好的解决方案。
关于c# - 如何使用 Linq (C#) 分隔所有连续的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4100375/