How to separate all consecutive Objects using Linq (C#)

后端 未结 6 626
长发绾君心
长发绾君心 2021-01-14 10:37

I have a List ... MyObject has a propert called LineId (integer)...

So, I need separate all consecutive LineId in List

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 11:28

    Hmm, I don't think linq is the cleanest solution to this problem. I think that the following code is probably far simpler and easier to read than any LINQ.

                List currentList = new List();
                List> finalList = new List>();
                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();
                        currentList.Add(myObjects[i]);
                    }
                }
                finalList.Add(currentList);
    

    I know you asked for linq, but I think this is probably a better solution.

提交回复
热议问题