LINQ 分组依据,然后选择不在分组依据中的多个列

本文关键字:选择 然后 LINQ | 更新日期: 2023-09-27 17:57:05

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

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

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

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();

有人可以帮忙吗?

LINQ 分组依据,然后选择不在分组依据中的多个列

你几乎就在那里 - 你缺少的只是组中的一个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将所有结果转储到平面列表中。

这对你有用吗?

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 });
对我来说,

我使用以下查询来执行过滤器客户并按 JobFunction 获取客户记录组。就我而言,添加.AsEnumerable() 在 where 解决问题之后。

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();