我需要帮助从emailaddresses列表中删除重复项。我需要添加代码以在emailaddresses类中对emailaddresses进行分组。由于电话号码不同,Sql返回重复的电子邮件地址。有什么建议?感谢。
这是我的代码: 的 1。类
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({
units: 'nautical'
}),
new ol.control.MousePosition({
coordinateFormat: function(coord) {
return ol.coordinate.toStringHDMS(coord);
},
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
})
]),
2。来自sql查询的数据
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; }
}
第3。代码
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
答案 0 :(得分:1)
如果我认为你是正确的,你需要得到不同的值,你可以这样做
List<Product> list = products
.GroupBy(a => a.Code )
.Select(g => g.First())
.ToList();
或
创建竞争对手,而不是试图找出不同的对象
完整代码的文章:DistinctBy in Linq (Find Distinct object by Property)
class ProductComparare : IEqualityComparer<product>
{
private Func<Product, object> _funcDistinct;
public ProductComparare(Func<Product, object> funcDistinct)
{
this._funcDistinct = funcDistinct;
}
public bool Equals(Product x, Product y)
{
return _funcDistinct(x).Equals(_funcDistinct(y));
}
public int GetHashCode(Product obj)
{
return this._funcDistinct(obj).GetHashCode();
}
}
var list2 = products.Distinct(new ProductComparare( a => a.Code ));
答案 1 :(得分:1)
虽然最好在返回之前过滤掉重复项,但这也会增加代码的复杂性。如果您的结果集很小,那么在您返回数据后进行过滤的内存和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();
}
}