List<Person> persons = null;
persons = new List<Person>();
persons.Add(new Person
{
Id = 1,
FirstName = "Chris",
LastName = "Cummings",
phn = 111223333,
comment="test"
});
persons.Add(new Person
{
Id = 2,
FirstName = "Chris",
LastName = "Cummings",
phn = 987654321,
comment=""
});
persons.Add(new Person
{
Id = 3,
FirstName = "John",
LastName = "Steinbeck",
phn = 111223333,
comment = "dfdf"
});
persons.Add(new Person
{
Id = 4,
FirstName = "fgg",
LastName = "hgh",
phn = 545,
comment = ""
});
从上面的列表中我想显示以下数据
如果姓氏和姓氏与任何人必须包含评论的人匹配,否则将删除没有评论的其他人
Id = 1,
FirstName = "Chris",
LastName = "Cummings",
phn = 111223333,
comment="test"
Id = 3,
FirstName = "John",
LastName = "Steinbeck",
phn = 111223333,
comment = "dfdf"
Id = 4,
FirstName = "fgg",
LastName = "hgh",
phn = 545,
comment = ""
答案 0 :(得分:3)
您可以使用GroupBy
并使用SelectMany
功能
var result =
persons.GroupBy(p => new { p.FirstName, p.LastName })
.SelectMany(g => g.Where(p => string.IsNullOrEmpty(p.Comment) == false));
如果您想要保留没有匹配人并且评论为空的人,您可以添加条件group.Count() == 1
var result =
persons.GroupBy(p => new { p.FirstName, p.LastName })
.SelectMany(g =>
{
var isSingle = g.Count() == 1;
return g.Where(p => isSingle || !string.IsNullOrEmpty(p.Comment))
});
答案 1 :(得分:0)
//Union the persons and use the comparer class
var result = persons.Union(persons, new PersonComparer()).Where(e=> !string.IsNullOrEmpty( e.comment));
//Use the below comparer class
public class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstName == y.FirstName && x.LastName == y.LastName;
}
public int GetHashCode(Person obj)
{
return obj.FirstName.GetHashCode() + obj.LastName.GetHashCode();
}
}