gpt4 book ai didi

C# 集合合并条目

转载 作者:行者123 更新时间:2023-12-03 05:29:33 26 4
gpt4 key购买 nike

    public class Contact
{
public string Name { get; set; }
public string Fax { get; set; }
public string Email {get; set; }
}

如果我有一个如下所示的联系人列表:

List<Contact> contactList = 
╔═════╦══════╦═════════════╗
║Name ║ Fax ║ Email ║
╠═════╬══════╬═════════════╣
║ a ║ 1 ║ ║
║ b ║ ║ b@email.com ║
║ c ║ 3 ║ c@email.com ║
║ a ║ ║ a@email.com ║
║ b ║ 2 ║ ║
╚═════╩══════╩═════════════╝

如何组合具有相同名称的条目并产生此结果?

╔═════╦══════╦═════════════╗
║Name ║ Fax ║ Email ║
╠═════╬══════╬═════════════╣
║ a ║ 1 ║ a@email.com ║
║ b ║ 2 ║ b@email.com ║
║ c ║ 3 ║ c@email.com ║
╚═════╩══════╩═════════════╝

这是我到目前为止尝试过的:

var result = contactList.Select(contact => contact.Name)
.Distinct()
.Select(name => contactList.First(contact => contact.Name == name))
.ToList();


foreach (var contact in contactList)
{
var c = result.First(r => r.Name == contact.Name);
c.Name = string.IsNullOrWhiteSpace(contact.Name) ? c.Name : contact.Name;
c.Fax = string.IsNullOrWhiteSpace(contact.Fax ? c.Fax : contact.Fax;
c.Email = string.IsNullOrWhiteSpace(contact.Email) ? c.Email : contact.Email;
}

有没有更有效的方法?

最佳答案

看起来您需要执行GroupBy,然后我假设这些值是空值,因此您只想获取第一个非空值。

var results = (from contact in constactList
group contact by contact.Name into contacts
select new Contact
{
Name = contacts.Key,
Fax = contacts.FirstOrDefault(c => c.Fax != null)?.Fax,
Email = contacts.FirstOrDefault(c => c.Email != null)?.Email
}).ToList();

或者在方法语法中

var results = constactList.GroupBy(contact => contact.Name)
.Select(contacts => new Contact
{
Name = contacts.Key,
Fax = contacts.FirstOrDefault(c => c.Fax != null)?.Fax,
Email = contacts.FirstOrDefault(c => c.Email != null)?.Email
}).ToList();

或者如果它们是空白字符串,您也可以这样做

Fax = contacts.FirstOrDefault(c => !string.IsNullOrWhiteSpace(c.Fax))?.Fax

如果您没有 C# 6,则执行以下操作

Fax = contacts.Where(c => !string.IsNullOrWhiteSpace(c.Fax)).Select(c => c.Fax).FirstOrDefault()

关于C# 集合合并条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518619/

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