如何使用Lambda返回不同行的Grouped数组

时间:2014-12-03 07:24:14

标签: c# lambda

我正在尝试从表中选择行。我需要在一列上执行GroupBy,然后在另一列上执行Distinct()。我想在结果中返回整行。

假设数据库表具有以下结构和数据:

GroupId = 1, To = "A", From = "B", Flag = True
GroupId = 1, To = "A", From = "C", Flag = True
GroupId = 1, To = "B", From = "A", Flag = True
GroupId = 1, To = "B", From = "C", Flag = False
GroupId = 1, To = "C", From = "A", Flag = True
GroupId = 1, To = "C", From = "B", Flag = True
GroupId = 2, To = "A", From = "B", Flag = True
GroupId = 2, To = "B", From = "C", Flag = True
GroupId = 2, To = "C", From = "A", Flag = True
GroupId = 2, To = "D", From = "C", Flag = True
GroupId = 2, To = "D", From = "A", Flag = False
GroupId = 2, To = "A", From = "B", Flag = True

以下代码行返回一个Groups数组,每个包含一个To字符串数组:

var test = db.LookupMap
    .Where(u => u.Flag == true)
    .GroupBy(u => u.GroupId, (key, group) => group.Select(m => m.To).Distinct())
    .ToArray(); 

我可以通过将m.To更改为m来获取对象数组:

.GroupBy(u => u.GroupId, (key, group) => group.Select(m => m).Distinct())

但这会破坏To列上的Distinct()。

如何返回对象数组(整行)而不是数组字符串?

注意:每个唯一的GroupId

的To列应该是不同的

1 个答案:

答案 0 :(得分:1)

使用其他GroupByFirst结合使用:

.GroupBy(u => u.GroupId,
        (key, group) => group.GroupBy(m => m.To).Select(g => g.First()))

它使用To属性值对没有第一组的项进行分组,然后从每个内部组中获取第一项。这是从moreLINQ获取与DistinctBy方法等效的方法的最简单方法 - 获取整行,但Distinct应仅在一个属性值上运行。