0

转换List<DayValue>为数组的最简单方法是什么,其中索引是月份中的日期:

class DayValue 
{
    public DateTime Day { get; set; }
    public object Value { get; set; }
}

我需要内联执行此操作,因为这将在 linq 中使用。我知道我可以遍历项目并设置数组值,但这需要完成

 list.FunctionThatConvertsItIntoArray()

例子:

输入列表:

{ 2012-11-01, "Value1" }
{ 2012-11-03, "Value2" }
{ 2012-11-05, "Value3" }

输出数组:

1 => "Value1"
2 => null
3 => "Value2"
4 => null
5 => "Value3"
6 => null
7 => null
8 => null    
9 => null 
10 => null
11 => null
12 => null
13 => null
14 => null
15 => null
16 => null
17 => null
18 => null
19 => null
20 => null
21 => null
22 => null
23 => null
24 => null
25 => null
26 => null
27 => null
28 => null
29 => null
30 => null
4

2 回答 2

1
var days = Enumerable.Range(1, 31)
                     .Select(i => list.Find(x => x.Day.Day == i))
                     .Select(d => d != null ? d.Value : null)
                     .ToArray();
于 2012-11-09T08:00:47.333 回答
0

这解决了我的问题:

Enumerable.Range(0, 31).Select(
    index => (list.FirstOrDefault(item => item.Day.Day == index) ?? new DayValue()).Value).ToArray();

完整的解决方案:

public class DayValue
{
    public DateTime Day { get; set; }
    public object Value { get; set; }
}

var list = new List<DayValue>();

list.Add(new DayValue { Day = new DateTime(2012, 11, 1), Value = "Value1" });
list.Add(new DayValue { Day = new DateTime(2012, 11, 3), Value = "Value2" });
list.Add(new DayValue { Day = new DateTime(2012, 11, 5), Value = "Value3" });

var result = Enumerable.Range(0, 31).Select(
    index => (list.FirstOrDefault(item => item.Day.Day == index) ?? new DayValue()).Value).ToArray();
于 2012-11-09T07:58:31.403 回答