c# - 如何使用 Linq (C#) 分隔所有连续的对象

标签 c# linq

我有一个 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/

相关文章:

c# - 我们如何使用 LINQ 从 asp.net mvc3 中的长字符串中提取短字符串?

c# - 获取通用接口(interface)的实现类型

linq - NHibernate Linq 提供者和 take() skip() 与急切获取

c# - 来自本地资源的字体系列资源

c# - 全局 Asax 与全局过滤器

c# - 将 Word 转换为 HTML,然后在网页上呈现 HTML

.net - LINQ 查询和 IDisposable

c# - 如何在 Roslyn 中为方法创建没有 ref 或 out 的命名参数?

c# - 将数据发布到 Flex/Flash (mxml) 应用程序

c# - 从两个数据表中选择 Linq to SQL 中的不同和日期差异