尝试在LINQ中组合两个表

时间:2016-03-29 12:03:31

标签: c# linq

说我有一个

TableA
string Name
string Description

TableB
string Name
string Value

TableA和TableB由Name连接。 (理论上,即不在DB中执行)

我想创建一个对象:

public MyObject
{
  string Name
  string Description
  List<string> Values
}

我想要了解如何使用LINQ组合这些。

var tableA = _oda.GetTableA();
var tableB = _oda.GetTableB();
var model = from a in tableA
join b in tableB on a.NAME equals b.NAME
    select new MyObject
    {
         Name= a.Name,
         Description = a.Description,
         Values = "<Not sure to get list of tableb.Value>" 
    };

2 个答案:

答案 0 :(得分:2)

如果是内部联接,您可以在加入后使用GroupBy

var tableA = new List<TableA> { new TableA { Name = "1", Description = "D1" }, new TableA { Name = "2", Description = "D2"} };
var tableB = new List<TableB> { new TableB { Name = "1", Value = "V1" }, new TableB { Name = "1", Value = "V2"} };

var result = tableA.Join(tableB, a => a.Name, b => b.Name, (a, b) => new { A = a, B = b})
    .GroupBy(k => k.A, e => e.B.Value)
    .Select(g => new MyObject
    {
        Name = g.Key.Name,
        Description = g.Key.Description,
        Values = g.ToList()
    });

foreach (var res in result)
{
    Console.WriteLine("Name: {0}, Description: {1}, Value: {2}", res.Name, res.Description, string.Join(", ", res.Values));
}

答案 1 :(得分:1)

没有尝试过代码,但是这样的事情应该可行。

var result = from a in TableA
             join b in TableB on a.Name equal b.Name
             group b.Value by a into g
             select new MyObject
             {
                Name = g.Key.Name,
                Description = g.Key.Description,
                Values = g.ToList()
             }