Home > Back-end >  C# select duplicate using group
C# select duplicate using group

Time:10-27

I would like to select only from non-blank Names where any Group contains same ID multiple times:

Data Setup

var a1 = new { id = 3, Name = "", Group = "GroupA" };
var a2 = new { id = 2, Name = "", Group = "GroupA" };
var a3 = new { id = 3, Name = "", Group = "GroupA" };
var b1 = new { id = 4, Name = "B", Group = "GroupB" };
var b2 = new { id = 5, Name = "B", Group = "GroupB" };
var b3 = new { id = 5, Name = "B", Group = "GroupB" };
List<dynamic> group = new List<dynamic>();
group.Add(a1);
group.Add(a2);
group.Add(a3);
group.Add(b1);
group.Add(b2);
group.Add(b3);

Query:

var query1 = group.ToList()
    .Where(s=>s.Name != "")
    .GroupBy(x =>x.Group)
    .Where(g => g.Count() > 1)
    .SelectMany(y => y)
    .ToList();
Console.WriteLine("output\n"   string.Join("\n", query1));

Returns

 id = 4, Name = B, Group = GroupB 
 id = 5, Name = B, Group = GroupB 
 id = 5, Name = B, Group = GroupB 

But what I wanted is the following:

 id = 5, Name = B, Group = GroupB 
 id = 5, Name = B, Group = GroupB 

What am I doing wrong?

CodePudding user response:

Group by id and/or Name depending on your needs

.GroupBy(x => new {x.id, x.Name})

Given

var list = new[]
{
   new {id = 3, Name = "", Group = "GroupA"},
   new {id = 2, Name = "", Group = "GroupA"},
   new {id = 3, Name = "", Group = "GroupA"},
   new {id = 4, Name = "B", Group = "GroupB"},
   new {id = 5, Name = "B", Group = "GroupB"},
   new {id = 5, Name = "B", Group = "GroupB"}
};

Usage

var results = list
   .Where(s => s.Name != "")
   .GroupBy(x => new {x.id, x.Name})
// .GroupBy(x => x.id) <- depending on your needs
   .Where(g => g.Count() > 1)
   .SelectMany(y => y);

foreach (var result in results)
   Console.WriteLine($"{result.id}, {result.Name}, {result.Group}");

Output

5, B, GroupB
5, B, GroupB

CodePudding user response:

You are applying GroupBy to Group property. Instead of Grouping by Group property, use id property,

Input

var list = new[]
{
    new {id = 3, Name = "", Group = "GroupA"},
    new {id = 2, Name = "", Group = "GroupA"},
    new {id = 3, Name = "", Group = "GroupA"},
    new {id = 4, Name = "B", Group = "GroupB"},
    new {id = 5, Name = "B", Group = "GroupB"},
    new {id = 5, Name = "B", Group = "GroupB"}
};

Solution:

var query1 = list.ToList()
    .Where(s=>s.Name != "")
    .GroupBy(x =>x.id)  
               //^^^^^ This change you need to do  
    .Where(g => g.Count() > 1)
    .SelectMany(y => y)
    .ToList();

Output

5, B, GroupB
5, B, GroupB

Try it online

  • Related