gpt4 book ai didi

c# - Linq - 将每个类(class)分组

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:14 25 4
gpt4 key购买 nike

我需要帮助从电子邮件地址列表中删除重复项。我需要添加代码以在电子邮件地址类中对电子邮件地址进行分组。由于电话号码不同,Sql 返回重复的电子邮件地址。有什么建议么?谢谢。

这是我的代码:<强>1。类

public class Student
{
public string StudentId { get; set; }
public string Gender { get; set; }
public List<EmailAddresses> emailAddresses { get; set; }
}

public class EmailAddresses
{
public string EmailAddress { get; set; }
}

<强>2。来自sql查询的数据

StudentId   EmailAddresses  IsPreferred Number  TelephoneType                                                                                               
123456789 maryjoe@gmail.com FALSE 5556565 Present Evening Phone
123456789 maryjoe@gmail.com FALSE 8885566 Permanent Day Phone
123456789 mary.joe@cuu.edu TRUE 5556565 Present Evening Phone
123456789 mary.joe@cuu.edu TRUE 8885566 Permanent Day Phone
456789123 dh@mycollege.edu TRUE 7513150 Business Day Phone
456789123 donna.hill@cu.edu TRUE 4123300 Present Day Phone
456789123 donna.hill@cu.edu FALSE 4123300 Present Day Phone

<强>3。代码

public List<Student> GetStudentData()
{
List<Student> dataStudent;
using (IDbConnection connection = RepositoryHelper.OpenConnection())
{
dataStudent = connection.Query<dynamic>(
"mystoredprocedure",
commandType: CommandType.StoredProcedure)
.GroupBy(x => x.StudentId)
.Select(x => new Student
{
StudentId = x.First().StudentId,
Gender = x.First().Gender,
emailAddresses = x.Select(ea => new EmailAddresses
{
EmailAddress = ea.emailAddresses
}).ToList()
}).ToList();

return dataStudent;
}
}

最佳答案

虽然在返回之前过滤掉重复项会更可取,但这也会增加代码的复杂性。如果你的结果集很小,返回数据后过滤的内存和 cpu 开销可能会很容易和清晰地得到你需要的结果。您可以使用自定义 IEqualityComparer 检查不同的结果,并在包含不同电子邮件地址的每个学生记录上创建一个新的 emailAddresses 列表。

public List<Student> GetStudentData()
{
List<Student> dataStudent;
using (IDbConnection connection = RepositoryHelper.OpenConnection())
{
dataStudent = connection.Query<dynamic>(
"mystoredprocedure",
commandType: CommandType.StoredProcedure)
.GroupBy(x => x.StudentId)
.Select(x => new Student
{
StudentId = x.First().StudentId,
Gender = x.First().Gender,
emailAddresses = x.Select(ea => new EmailAddresses
{
EmailAddress = ea.emailAddresses
}).ToList()
}).ToList();

dataStudent.ForEach(x => x.emailAddresses = x.emailAddresses
.Distinct(new StudentEmailEqualityComparer()).ToList());

return dataStudent;
}
}

public class StudentEmailEqualityComparer : IEqualityComparer<EmailAddresses>
{

public bool Equals(EmailAddresses x, EmailAddresses y)
{
return x.EmailAddress.Equals(y.EmailAddress);
}

public int GetHashCode(EmailAddresses obj)
{
return obj.EmailAddress.GetHashCode();
}
}

关于c# - Linq - 将每个类(class)分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31052520/

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