gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:20 24 4
gpt4 key购买 nike

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

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 分组,然后为每个组创建该组所有项目的聚合,并在遍历具有该数据的每个对象时填写成员.

关于c# - 具有重复 ID 的集合展平为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com