gpt4 book ai didi

c# - 使用 Linq 按列表中的多列分组并标记所有重复项

转载 作者:行者123 更新时间:2023-11-30 15:09:02 32 4
gpt4 key购买 nike

我想使用 LinQ 查询列表并找到重复的人(定义了重复项具有相同的名字、姓氏和出生日期)并标记每个重复的人的StateOfData 属性包含字符串“duplicate”,每个人的 StateOfData 属性包含字符串“unique”。

public  Class Person 
{
public string PersonFirstName { get; set; }
public string PersonLastName { get; set; }
public datetime PersonDateOfBirth { get; set; }
public string StateOfData{ get; set }

public Person (string firstName, string lastName, dateTime dateOfBirth,string state)
{
this.PersonFirstName = firstName;
this.PersonLastName = lastName;
this.PersonDateOfBirth = dateOfBirth;
this.StateOfData = state;
}


}


IList<Person> personsList = new List<Person>();
Person pers = new Person("Diane","Jones","1967-01-01","");
personsList.add(pers);
Person pers = new Person("Diane","Jones","1967-01-01","");
personsList.add(pers);
Person pers = new Person("John","Jones","1967-01-01","");
personsList.add(pers);

人员列表的结果应为:

“黛安”,“琼斯”,“1967-01-01”,“重复”
“黛安”,“琼斯”,“1967-01-01”,“重复”
“约翰”,“琼斯”,“1967-01-01”,“独一无二”

如有任何帮助,我们将不胜感激

最佳答案

var theLookup = personList
.GroupBy(p => new {p.PersonFirstName, p.PersonLastName, p.PersonDateOfBirth})
.ToLookup(g => g.Skip(1).Any() ? "duplicate" : "unique");

foreach(var lookupEntry in theLookup)
{
string stateOfData = lookupEntry.Key;
foreach(Person p in lookupEntry.SelectMany(g => g))
{
p.StateOfData = stateOfData;
}
}

关于c# - 使用 Linq 按列表中的多列分组并标记所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909013/

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