我想在列表中按名称值查找重复项。我在下面列举了一些我想要实现的目标。
如果我循环查询,我可以输出重复的名称值,但是我也想将地址和ID值输出到表中。
可以这样做吗?
public class Record
{
public int Id { get; set; }
public string Name{ get; set; }
public string Address{ get; set; }
}
我使用以下查询找到重复项:
var query = record.GroupBy(s => s.name).Where(s => s.Count() > 1);
答案 0 :(得分:3)
如果您想简单地返回所有形成重复的记录,并且至少有一个其他记录的名称,那么您几乎就是正确的。
这样做:
var query =
record
.GroupBy(s => s.Name)
.Where(s => s.Count() > 1)
.SelectMany(r => r);
所以,如果我从这开始:
var record = new[]
{
new { Id = 1, Name = "Joe", Address = "X" },
new { Id = 2, Name = "Barry", Address = "Y"},
new { Id = 3, Name = "Joe", Address = "A"},
new { Id = 4, Name = "Mike", Address = "B"},
new { Id = 5, Name = "Barry", Address = "B"},
new { Id = 6, Name = "Joe", Address = "B"},
};
我离开了这个:
答案 1 :(得分:0)
以下适用于我:
var query = records.GroupBy(s => s.Name)
.Where(s => s.Count() > 1)
.SelectMany(x => x.Select(y => new Record{ Id = y.Id, Name = y.Name, Address = y.Address}));
使用
进行测试var records = new [] {
new Record {Address = "A", Id = 1, Name = "Tim"},
new Record {Address = "B", Id = 2, Name = "Tim"},
new Record {Address = "C", Id = 3, Name = "Tim"},
new Record {Address = "D", Id = 4, Name = "Hans"}
};
获取名为Records
的前三个Tim
。
答案 2 :(得分:0)
有两种方法可以解决这个问题:
首先,您需要做的是迭代分组记录:
var duplicates = records.GroupBy(r => r.Name)
.Where(g => g.Count() > 1);
foreach(var duplicateGroup in duplicates)
{
Console.WriteLine("Duplicates for: {0}", duplicateGroup.Key);
foreach(var item in duplicateGroup)
{
Console.WriteLine("Id: {0}, Address: {1}", item.Id, item.Address);
}
}
上面的代码将输出重复项的Name
,然后输出重复组中每条记录的Id
和Address
值。
如果要加载表格中的所有重复项(例如将其导出到Excel文件),则需要使用以下内容:
var duplicates = records.GroupBy(r => r.Name)
.Where(g => g.Count() > 1)
.SelectMany(g => g.ToArray());
foreach(var duplicate in duplicates)
{
Console.WriteLine("Name: {0}, Id: {1}, Address: {2}", duplicate.Name, duplicate.Id, duplicate.Address);
}
此代码块将仅输出第一列中包含重复Name
的重复项,以便更容易查看记录。
答案 3 :(得分:-1)
这应该有效(未经测试):
var grouped = record.GroupBy(s => s.Name).Where(s => s.Count() > 1);
var result = grouped.SelectMany(c => c.Select(p => p.Address));