如何加入不同的属性对象集合

时间:2017-11-03 20:02:59

标签: c# entity-framework linq

我有一个我的问题类列表

var firstList = new List<object> {
    new { id =1, Name = "item-1"},
    new { id =2, Name = "item-2"},
    new { id =3, Name = "item-3"},
    new { id =4, Name = "item-4"}
}

我的第二个清单就像这样

var secondList = new List<Issue> {
    new Issue{ id =1, Date = "01.01.2017"},
    new Issue{ id =2, Date = "01.02.2017"}
}

所以我想创建一个这样的新列表。 (相同的id对象将是isPlanned = true)

var firstList = new List<object> {
    new { id =1, Name = "item-1", isPlanned=true, Date = "01.01.2017"},
    new { id =2, Name = "item-2", isPlanned=true, Date = "01.02.2017"},
    new { id =3, Name = "item-3", isPlanned=false },
    new { id =4, Name = "item-4", isPlanned=false }
}

我该怎么做linq函数或lambda操作?

2 个答案:

答案 0 :(得分:0)

您可以使用左连接:

var items = new[] {
    new { id =1, Name = "item-1"},
    new { id =2, Name = "item-2"},
    new { id =3, Name = "item-3"},
    new { id =4, Name = "item-4"}
};
var issues = new[] {
    new { id =1, Date = "01.01.2017"},
    new { id =2, Date = "01.02.2017"}
};
var joined = from item in items
             join issue in issues on item.id equals issue.id into gj
             from sub in gj.DefaultIfEmpty()
             select new { item.id, item.Name, isPlanned=sub?.Date != null, sub?.Date };
foreach (var t in joined) {
    Console.WriteLine("{0} {1} {2} {3}", t.id, t.Name, t.isPlanned, t.Date);
}

当缺少日期时,结果将为null,即

new { id =1, Name = "item-1", isPlanned=true,  Date = "01.01.2017"},
new { id =2, Name = "item-2", isPlanned=true,  Date = "01.02.2017"},
new { id =3, Name = "item-3", isPlanned=false, Date = null },
new { id =4, Name = "item-4", isPlanned=false, Date = null }

Demo.

答案 1 :(得分:0)

如果你想使用lambda表达式,你可以通过以下方式实现:

List<Foo> foos = new List<Foo>()
{
    new Foo(){ Id = 1, Name = "item-1"},
    new Foo(){ Id = 2, Name = "item-2"},
    new Foo(){ Id = 3, Name = "item-3"},
    new Foo(){ Id = 4, Name = "item-4"}
};

List<Bar> bars = new List<Bar>()
{
    new Bar(){ Id = 1, Date = "01.01.2017"},
    new Bar(){ Id = 2, Date = "01.02.2017"}
};

IEnumerable<dynamic> result = foos.GroupJoin(bars,
    f => f.Id,
    b => b.Id,
    (foo, bar) => new
    {
        Id = foo.Id,
        Name = foo.Name,
        isPlanned = String.IsNullOrEmpty(bar.SingleOrDefault()?.Date),
        Date = bar.SingleOrDefault()?.Date
    });

这是类

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Bar
{
    public int Id { get; set; }
    public string Date { get; set; }
}

我也从其他答案的评论中注意到您无法使用C#6.0,因此本节不适合您

isPlanned = String.IsNullOrEmpty(bar.SingleOrDefault()?.Date),
Date = bar.SingleOrDefault()?.Date

您可以使用以下内容替换它:

isPlanned = bar.SingleOrDefault() == null ? false : String.IsNullOrEmpty(bar.SingleOrDefault().Date),
Date = bar.SingleOrDefault() == null ? null : bar.SingleOrDefault().Date