Reputation: 1688
I'm trying to write a program that shows duplicate records to the user to correct the data or remove the duplicate rows. It works, but I had to put a Where clause in my lambda expression to get this working. How can I remove this useless clause?
Where(d => d.Id > 0) at line 22.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
static void Main(string[] args)
{
List<Person> dt = new List<Person>();
dt.Add(new Person() { Id = 1, Name = "MICHAEL JACKSON", Age = 50 });
dt.Add(new Person() { Id = 2, Name = "MICHAEL JACKSON", Age = 51 });
dt.Add(new Person() { Id = 3, Name = "JOHN LENNON", Age = 40 });
dt.Add(new Person() { Id = 4, Name = "JOHN LENNON", Age = 41 });
dt.Add(new Person() { Id = 5, Name = "ELVIS PRESLEY", Age = 42 });
var duplicates = dt.AsEnumerable().GroupBy(r => r.Name).Where(gr => gr.Count() > 1).ToList();
if (duplicates.Any())
{
var query = duplicates.SelectMany(c => c.Where(d => d.Id > 0)).AsQueryable();
foreach (var item in query)
Console.WriteLine(String.Format("{0} - {1}", item.Name, item.Age));
}
else
Console.WriteLine("No records duplicates.");
Console.ReadLine();
}
}
This is just sample code, my code does a lot of other checks, but if somebody knows how to remove this clause it will be very helpful to me. I think it could impact performance.
Upvotes: 1
Views: 697
Reputation: 7346
thats becouse duplicates
is the grouped by object. try this if you only want to show the name:
var query = duplicates.Select(c => c.Key);
foreach (var item in query)
Console.WriteLine(String.Format("{0}", item));
try this if you want to show repeated ages:
var query = duplicates.SelectMany(i => i);
foreach (var item in query)
Console.WriteLine(String.Format("{0} - {1}", item.Name, item.Age));
Upvotes: 1
Reputation: 103595
This works for me.
var query = duplicates.SelectMany(c => c).AsQueryable();
Upvotes: 1
Reputation: 9417
this here also works:
List<Person> dt = new List<Person>();
dt.Add(new Person() { Id = 1, Name = "MICHAEL JACKSON", Age = 50 });
dt.Add(new Person() { Id = 2, Name = "MICHAEL JACKSON", Age = 51 });
dt.Add(new Person() { Id = 3, Name = "JOHN LENNON", Age = 40 });
dt.Add(new Person() { Id = 4, Name = "JOHN LENNON", Age = 41 });
dt.Add(new Person() { Id = 5, Name = "ELVIS PRESLEY", Age = 42 });
var duplicates = dt.GroupBy(r => r.Name).Where(gr => gr.Count() > 1).ToList();
if (duplicates.Any())
{
foreach (var item in duplicates)
Console.WriteLine(String.Format("{0} - {1}", item.Key, string.Join(",", item.Select(p => p.Age))));
}
else
Console.WriteLine("No records duplicates.");
Console.ReadLine();
Upvotes: 2