c# - 在 LINQ 中对相似列进行分组并连接其他列

标签 c# linq linq-group

我有以下类(class)

public class InvoiceRO 
{
    public int ID{ get; set; }

    public string Address { get; set; }

    public string Reference1 { get; set; }

    public string DNNumber { get; set; }

    public string QuotationNumber { get; set; }

}

这里我有数据如下

ID   Address    Reference1  DNNumber   QuotationNumber
----------------------------------------------------------
1    add1           ref1      d001      q001
2    add1           ref1      d001      q002
3    add1           ref1      d002      q003

我只需要一行作为输出,因此前 2 列值将相等并且仅得到一个,最后 2 列将连接并检索为逗号分隔值。最终输出将是

ID   Address    Reference1  DNNumber        QuotationNumber
----------------------------------------------------------
1    add1           ref1      d001, d002      q001, q002, q003

如何在 LINQ 中进行这样的分组?

最佳答案

您可以使用GroupBy,然后使用String.Join连接字符串:

invoices.GroupBy(i => new {i.Address, i.Reference1})
        .Select(g => new InvoiceRO {
                        ID              = g.First().ID, 
                        Address         = g.Key.Address, 
                        Reference1      = g.Key.Reference1,
                        DNNumber        = string.Join(", ", g.Select(i => i.DNNumber)),
                        QuotationNumber = string.Join(", ", g.Select(i => i.QuotationNumber))
                        }

关于c# - 在 LINQ 中对相似列进行分组并连接其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094188/

相关文章:

C# 图形算法库

c# - 尝试使用 LINQ to SQL 创建节点树会产生 NotSupportedException

c# - 如何在 EF 中选择按日期分组的多个计数

c# - 如何使用 Linq 执行 IN 语法

c# - 这个LINQ表达式的解释

c# - 如何对分组列表的列表进行分组?

c# - 具有嵌套组的动态 linq 查询

c# - 排除字符串开头和结尾的特殊字符

c# - Dapper DynamicParameters 对象是否可以像参数字典一样被枚举?

c# - 使用 Linq 选择多个属性