linq中的分组和更新属性

时间:2013-12-26 09:59:51

标签: c# linq

我有以下

的对象集合
class Stream
{
    string PeriodName {set;get;}
    string StreamName{set;get;}
    string Index{set;get;}
}

在不同的Period Name下可能有N个重复流,比如

PeriodName ="A"
StreamName ="Oil"

PeriodName ="B"
StreamName ="Oil"

PeriodName ="C"
StreamName ="Oil"

PeriodName ="A"
StreamName ="Petrol"

PeriodName ="B"
StreamName ="Petrol"

PeriodName ="A"
StreamName ="Diesel"

我想通过StreamName对这些对象进行分组并插入索引号。 预期结果是

PeriodName ="A"
StreamName ="Oil"
Index=1

PeriodName ="B"
StreamName ="Oil"
Index=1

PeriodName ="C"
StreamName ="Oil"
Index=1

PeriodName ="A"
StreamName ="Petrol"
Index=2

PeriodName ="B"
StreamName ="Petrol"
Index=2

PeriodName ="A"
StreamName ="Diesel"
Index=3

我如何在C#中实现同样的目标?

2 个答案:

答案 0 :(得分:2)

list =list.GroupBy(l=>l.StreamName )
   .SelectMany((g,index) => g.Select(x=>
                    new Stream(){
                        PeriodName =x.PeriodName, 
                        StreamName =x.StreamName, 
                        Index =(index+1).ToString()})).ToList();

答案 1 :(得分:0)

如果你想更新现有对象的Index而不是创建新对象,你可以使用它,

streamList = streamList.GroupBy(stream => stream.StreamName)
             .SelectMany((streamGroup, index) => streamGroup.Select(stream =>
             {
                 stream.Index = index+1;
                 return stream;
             })).ToList();