我将三个值存储在这样的列表中:
var mylist = new List<(int Id, string name, string surname)>();
示例数据:
1 | John | Miller
2 | Jessica | Scot
3 | Robert | Johnes
4 | John | Miller
如何区分以仅获取名称和姓氏不重复的记录(不计算ID),因此结果是:
2 | Jessica | Scot
3 | Robert | Johnes
答案 0 :(得分:3)
最后,问题解决后,我将提出以下建议。
这将是我用来组织表条目的类结构。
public class MyTable
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public MyTable(int Id, string Name, string Surname)
{
this.Id = Id;
this.Name = Name;
this.Surname = Surname;
}
}
然后,这将是我的测试方法
[Fact]
public void RemovesAllInstancesOfDuplicateEntries()
{
var mylist = new List<MyTable>();
mylist.Add(new MyTable(1 , "John" , "Miller"));
mylist.Add(new MyTable(2 , "Jessica", "Scot"));
mylist.Add(new MyTable(3 , "Robert", "Johnes"));
mylist.Add(new MyTable(4 , "John", "Miller"));
var actual = new MySUT().RemoveAllInstancesOfDuplicates(mylist);
Assert.Equal(2, actual.Count);
Assert.Equal(2, actual[0].Id);
Assert.Equal(3, actual[1].Id);
}
而且,我对测试的实现如下
public List<MyTable> RemoveAllInstancesOfDuplicates(List<MyTable> myTable)
{
List<MyTable> withoutAllInstancesOfDuplicates = new List<MyTable>();
foreach(MyTable entry in myTable)
{
if (myTable.Count(row =>
string.Equals(row.Name, entry.Name) &&
string.Equals(row.Surname, entry.Surname)) == 1)
{
withoutAllInstancesOfDuplicates.Add(entry);
}
}
return withoutAllInstancesOfDuplicates;
}
答案 1 :(得分:1)
您可以使用Where
和Any
的组合,如下所示:
var noDupes = mylist
.Where(a => !myList
.Any(b => b.Id != a.Id && b.name == a.name && b.surname == a.surname));
这将返回一个IEnumerable<T>
,其中T
是仅包含杰西卡和罗伯特的值元组。
答案 2 :(得分:-1)
var mylist = originalList
.GroupBy(x => x.name + x.surname) //or any other combination
.Select(group => group.First())
.ToList();
答案 3 :(得分:-1)
您希望唯一性的列上的组,并计算这些组上元素的数量。您只需要带有1的元素。
mylist
.GroupBy(x => new {x.Name, x.Surname})
.Where(grp => grp.Count() == 1)
.Select(grp => grp.First());