开发者

How to recalculate elements with IEnumerable.Select?

开发者 https://www.devze.com 2023-02-25 03:36 出处:网络
IEnumerable<MyType> list = new List<MyType>{ new{Num=0, Text=\"ABC\"}, new{Num=0, text=\"DEF\"},
IEnumerable<MyType> list = new List<MyType>{
    new{Num=0, Text="ABC"},
    new{Num=0, text="DEF"},
    new{Num=0, text="GHI"} }

I need to get element index in Num field:

IEnumerable<MyType> resul开发者_JAVA百科t = new List<MyType>{
    new{Num=1, Text="ABC"},
    new{Num=2, text="DEF"},
    new{Num=3, text="GHI"} }

Is it possible to do it with some LINQ-based construction?


var result = list.Select(
    (element, index) => new MyType { Num = index + 1, Text = element.Text }
);


var newList = list.Zip(Enumerable.Range(1, list.Length),
    (item, i) => new { Num = i, item.text}).ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消