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

时间:2016-07-15 18:21:19

标签: 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();

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

你几乎就在那里 - 你所缺少的只是来自小组的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
    }));
来自每个组的

Select执行所需字段的投影,而SelectMany将所有结果转储到平面列表中。

答案 1 :(得分:2)

这对你有用吗?

var groupsWithDuplicates = tableQueryable
    .Where(c => !string.IsNullOrWhiteSpace(c.first_name) || !string.IsNullOrWhiteSpace(c.last_name))
    .GroupBy(c => new { FirstName = c.first_name ?? "", LastName = c.last_name ?? "" })
    .Where(group => group.Count() > 1) // Only keep groups with more than one item
    .ToList();

var duplicates = groupsWithDuplicates
    .SelectMany(g => g) // Flatten out groups into a single collection
    .Select(c => new { c.first_name, c.last_name, c.customer_rep_id });

答案 2 :(得分:-1)

对我来说,我使用以下查询来过滤客户并通过 JobFunction 获取客户记录组。在我的情况下,在 where 解决问题之后添加 .AsEnumerable() 后问题得到解决。

var query = _context.Customer
                 .Where(x => x.JobTitle.ToUpper().Contains(searchText.ToUpper())).AsEnumerable()
                .GroupBy(item => item.JobFunction,
                    (key, group) => new {
                        JobFunction = key,
                        CustomerRecords = group.ToList().Select(c => c).ToList()
                    })
                .ToList();
相关问题