I have a List<Demo>
public class Demo
{
public Demo()
{
}
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
The Id property is unique for every record in the list.
How can I get a List<Demo>
from the original List<Demo>
with all the duplicates where the Name and Title are same.
What I did so far but what I get is one single record:
List<Demo> demo = new List<Demo>();
demo.Add(new Demo()
{
Id = 1,
Name = "Demo",
Title = "A"
});
demo.Add(new Demo()
{
Id = 2,
Name = "Demo",
Title = "A"
});
demo.Add(new Demo()
{
Id = 3,
Name = "Demo",
Title = "A"
});
demo.Add(new Demo()
{
Id = 4,
Name = "Demo1",
Title = "A"
});
demo.Add(new Demo()
{
Id = 5,
Name = "Demo2",
Title = "A"
});
and then i am doing:
var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
.Where(t => t.Count() > 1)
.Select(g => g.Key).ToList();
From the example above I should get a List<Demo>
with the first 3 items where the ids are:1,2,3 because Name and Title are same.
It sounds like all you're missing is a SelectMany
call. Currently you're creating all the appropriate groups and filtering down to groups with more than one entry - but if you want a single flat list, you need to flatten those groups back to their elements:
var duplicates = demo
.GroupBy(t => new { t.Name, t.Title })
.Where(t => t.Count() > 1)
.SelectMany(x => x) // Flatten groups to a single sequence
.ToList();
Note that this doesn't mean every entry in the resulting list will have the same name and title. It does mean that every entry will have a name/title combination in common with at least one other entry.
See more on this question at Stackoverflow