我有一个数字列表:
List<Int32> numbers = new List<Int32> { 1, 2, 5, 6, 18, 28, 40, 62 };
以及以下课程:
public class Measure {
public DateTime Created { get; set; }
public Int32 Value { get; set; }
}
我需要创建一个测量列表,其中:
因此Measure的列表类似于:
DateTime.Now, 1
DateTime.Now.AddDays(1), 2
DateTime.Now.AddDays(2), 5
...
是否可以使用Linq创建此列表?
答案 0 :(得分:1)
让我们尝试Select((value, index) => ...)的构造:
List<Int32> numbers = new List<Int32> { 1, 2, 5, 6, 18, 28, 40, 62 };
List<Measure> result = numbers
.Select((value, index) => new Measure() {
Created = DateTime.Now.AddDays(index),
Value = value
})
.ToList();
答案 1 :(得分:0)
是的,您可以:
List<Int32> numbers = new List<Int32> { 1, 2, 5, 6, 18, 28, 40, 62 };
int dayCounter = 0;
var measureList = numbers.Select(
x => new Measure
{
Value = x,
Created = DateTime.Now.AddDays(dayCounter++)
}).ToList();