如何使用Linq(C#)分隔所有连续的对象 [英] How to separate all consecutive Objects using Linq (C#)

查看:120
本文介绍了如何使用Linq(C#)分隔所有连续的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<MyObject> ... MyObject有一个称为 LineId (整数)...

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

因此,我需要在列表中分隔所有连续的LineId ...

So, I need separate all consecutive LineId in List ...

示例:

List<MyObject> :

LineId =1
LineId =1
LineId =1
LineId =2
LineId =1
LineId =2

结果必须为4个分隔的列表:

The result must be 4 separeted lists:

LineId =1
LineId =1
LineId =1
-------------
LineId =2
-------------
LineId =1
-------------
LineId =2

因此,我必须分隔所有连续的LineId ...

So, I must separate all consecutive LineId ...

有没有一种简单的方法可以使用Linq做到这一点?

Is there an easy way to do that using Linq?

谢谢

推荐答案

这看起来很丑,但想法很明确,我认为它可行:

This looks ugly but the idea is clear and I think it works:

var agg = list.Aggregate(
    new List<List<Line>>(),
    (groupedLines, line) => {
        if (!groupedLines.Any()) {
            groupedLines.Add(new List<Line>() { line });
        }
        else {
            List<Line> last = groupedLines.Last();
            if (last.First().LineId == line.LineId) {
                last.Add(line);
            }
            else {
                List<Line> newGroup = new List<Line>();
                newGroup.Add(line);
                groupedLines.Add(newGroup);
            }
        }
        return groupedLines;
    }
);

这里我假设您有:

class Line { public int LineId { get; set; } }

List<Line> list = new List<Line>() {
    new Line { LineId = 1 },
    new Line { LineId = 1 },
    new Line { LineId = 1 },
    new Line { LineId = 2 },
    new Line { LineId = 1 },
    new Line { LineId = 2 }
};

现在,如果我执行

foreach(var lineGroup in agg) {
    Console.WriteLine(
        "Found {0} consecutive lines with LineId = {1}",
        lineGroup.Count,
        lineGroup.First().LineId
    );
    foreach(var line in lineGroup) {
        Console.WriteLine("LineId = {0}", line.LineId);
    }
}

我知道了

Found 3 consecutive lines with LineId = 1
LineId = 1
LineId = 1
LineId = 1
Found 1 consecutive lines with LineId = 2
LineId = 2
Found 1 consecutive lines with LineId = 1
LineId = 1
Found 1 consecutive lines with LineId = 2
LineId = 2

打印在控制台上.

这篇关于如何使用Linq(C#)分隔所有连续的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆