构建按组收集记录的linq查询

时间:2017-09-12 08:57:56

标签: c# entity-framework linq

实际情况很简单,但在linq中处理它需要比我更多的exp ... 有3个表

Table1
ID Column
1   val1
2   val2
Table2
ID Column
1   val3
2   val4
Table3
ID Column
1   val5
2   val6

我需要这样一个返回的查询;

TableResult:

Row ID Column Type
1   1   val1  table1
2   2   val2  table1
3   1   val3  table2
4   2   val4  table2
5   1   val5  table3
6   2   val6  table3

在网上搜索并开始如下,但无法计算如何处理技巧创建“类型”,合并记录等。

  from t1 in table1 
    join t2 in table2 on t1.id equals t2.id
    join t3 in table3 on t1.id equals t3.id
    select new {...}

2 个答案:

答案 0 :(得分:2)

您已经接受了答案,因此我不知道这是否是您想要的,但它会生成您在帖子中指定的输出。

因为你只使用了1和2的Id值,所以不清楚你是否真的想要执行Join或者只是将所有行的集合放到一个结果中。

反正:

struct TableStructure
{
    public int Id { get; set; }
    public string Column { get; set; }
}

var t1 = new List<TableStructure>() { new TableStructure { Id = 1, Column = "val1" }, new TableStructure { Id = 2, Column = "val2" } };
var t2 = new List<TableStructure>() { new TableStructure { Id = 1, Column = "val3" }, new TableStructure { Id = 2, Column = "val4" } };
var t3 = new List<TableStructure>() { new TableStructure { Id = 1, Column = "val5" }, new TableStructure { Id = 2, Column = "val6" } };

var result = ((from row1 in t1 select new { row1.Id, row1.Column, SourceTable = "table1" })
        .Union(from row2 in t2 select new { row2.Id, row2.Column, SourceTable = "table2" })
        .Union(from row3 in t3 select new { row3.Id, row3.Column, SourceTable = "table3" }))
        .AsEnumerable().Select((row, index) => new { RowNum = index + 1, row.Id, row.Column, row.SourceTable });

result.ToList().ForEach(row => Console.WriteLine($"{row.RowNum}, {row.Id}, {row.Column}, {row.SourceTable}"));

输出:

1, 1, val1, table1
2, 2, val2, table1
3, 1, val3, table2
4, 2, val4, table2
5, 1, val5, table3
6, 2, val6, table3

答案 1 :(得分:1)

与你所做的相同,最后尝试了Distinct。查询语法为:

var List = (from t1 in dbContext.table1
                  join t2 in dbContext.table2 on t1.ID equals t2.ID
                  join t3 in dbContext.table3 on t1.ID equals t3.ID
                  select new
                  {
                   //t1.DesiredColumnName,
                   //t2.DesiredColumnName,
                   //t3.DesiredColumnName,
                   //so on
                  }).Distinct().ToList();