Skip to main content
 首页 » 编程设计

c#之具有重复 ID 的集合展平为一行

2024年02月04日30insus

我有一个集合,问题是我试图将它展平成一行。

Example 
ID      name         description  name2      Description2 
555     newname      a descript 
555                               name2      Description2name 
543     onename      myname      

结果应该是什么样子。

Example final 
ID      name         description  name2      Description2 
555     newname      a descript   name2      Description2name  
543     onename      myname 

基本上使用 linq 语句然后 list.Add(addlist) 将列表添加到我的 DTO 后,我将使用 foreach 循环。 不确定最终结果应该如何组合以产生最终结果,如上例所示。

请您参考如下方法:

不确定它的表现如何,但它确实有效 :)

using System; 
using System.Collections.Generic; 
using System.Linq; 
 
public class Program 
{ 
    public static void Main() 
    { 
        var dataItems = new List<Data> 
        { 
            new Data { ID = 555, Name = "newname", Description = "a descript" }, 
            new Data { ID = 555, Name2 = "name2", Description2 = "Description2name" }, 
            new Data { ID = 543, Name = "onename", Description = "myname" }, 
        }; 
 
        var aggregate = dataItems 
            .GroupBy(x => x.ID, x => x) 
            .Select(g => g.Aggregate((current, next) => 
            { 
                current.Description = current.Description ?? next.Description; 
                current.Description2 = current.Description2 ?? next.Description2; 
                current.Name = current.Name ?? next.Name; 
                current.Name2 = current.Name2 ?? next.Name2; 
                return current; 
            })); 
 
        foreach (var item in aggregate) 
        { 
            Console.WriteLine($"{item.ID}\t{item.Name}\t{item.Description}\t{item.Name2}\t{item.Description2}"); 
        } 
    } 
} 
 
 
public sealed class Data 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string Name2 { get; set; } 
    public string Description { get; set; } 
    public string Description2 { get; set; } 
} 

想法是按 ID 分组,然后为每个组创建该组所有项目的聚合,并在遍历具有该数据的每个对象时填写成员.