linq group by 并选择不在 group by 中的多个列

Mik*_*ner 4 c# linq

我正在尝试使用 linq - c# 选择不在组中的多个列。

使用 linq,我尝试按 ISNULL(fieldOne,''),ISNULL(fieldTo,'') 分组,然后为每个组选择 field_One、field_Two、field_Three。因此,对于 group by 将返回的每一行,我想看到许多行。

到目前为止,我有以下内容,但似乎无法选择所有需要的列。

var xy = tableQueryable.Where(
            !string.IsNullOrEmpty(cust.field_One)
            || ! string.IsNullOrEmpty(ust.field_Two)
            ).GroupBy(cust=> new { field_One= cust.field_One ?? string.Empty, field_Tow = cust.field_Two  ?? string.Empty}).Where(g=>g.Count()>1).AsQueryable();
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

das*_*ght 7

您几乎就在那里 - 您所缺少的只是Select来自该组的一个:

var xy = tableQueryable
    .Where(!string.IsNullOrEmpty(cust.first_name) || ! string.IsNullOrEmpty(ust.lastName))
    .GroupBy(cust=> new { first_name = cust.first_name ?? string.Empty, last_name = cust.last_name ?? string.Empty})
    .Where(g=>g.Count()>1)
    .ToList() // Try to work around the cross-apply issue
    .SelectMany(g => g.Select(cust => new {
        Id = cust.Id
    ,   cust.FirstName
    ,   cust.LastName
    ,   cust.RepId
    }));
Run Code Online (Sandbox Code Playgroud)

Select从每个组中对您想要的字段进行投影,同时SelectMany将所有结果转储到一个平面列表中。