Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
Public Class A
{
public int ID{get;set;}
public list<b> lstB {get;set;}
}

Public Class B
{
Public int ID{get;st;}
Public string Name{get;st;}
Public string Path{get;st;}
}



how i can write linq query to find duplicate Names from List of Class A

What I have tried:

lstDocumentsWithError = lstA.GroupBy(x => x.lstB).SelectMany(g => g.Skip(1)).ToList();
Posted
Updated 19-May-17 6:43am
v2

1 solution

Depending on situation...

I've tested below queries on that list:
C#
List<A> lstA = new List<A>
		{
			new A(){
				ID = 1, lstB = new List<b>()
					{
						new B(){ID = 1, Name="A", Path="C"},
						new B(){ID = 2, Name="A", Path="D"},
						new B(){ID = 3, Name="B", Path="E"},
						new B(){ID = 4, Name="C", Path="F"},
						new B(){ID = 5, Name="D", Path="G"}
					}},
			new A(){
				ID = 2, lstB = new List<b>()
					{
						new B(){ID = 6, Name="D", Path="C"},
						new B(){ID = 7, Name="E", Path="D"},
						new B(){ID = 8, Name="E", Path="E"},
						new B(){ID = 9, Name="F", Path="F"},
						new B(){ID = 10, Name="F", Path="G"}
					}},
			new A(){
				ID = 3, lstB = new List<b>()
					{
						new B(){ID = 11, Name="F", Path="C"},
						new B(){ID = 12, Name="G", Path="D"},
						new B(){ID = 13, Name="H", Path="E"},
						new B(){ID = 14, Name="H", Path="F"},
						new B(){ID = 15, Name="H", Path="G"}
					}},
		};


If you would like to find duplicated names of class B (A class is ignored) on entire lstA, try this:
C#
var lstDocumentsWithError = lstA
    .SelectMany(x=>x.lstB)
    .GroupBy(x => x.Name)
    .Where(grp=>grp.Count()>1)
    .Select(grp=> new {Name = grp.Key, Count = grp.Count()})
    .ToList();


Result:
Name Count
A    2 
D    2 
E    2 
F    3 
H    3


But if you would like to compare names only inside class A, you have to change above code to:
C#
var lstDocumentsWithError1 = lstA
    .SelectMany(x => 
			x.lstB.GroupBy(y=>y.Name)
				.Where(grp=>grp.Count()>1)
				.Select(z=> new
					{
						AID = x.ID,
						Name = z.Key,
						Count = z.Count()
					})
		);


Result:
AID Name Count
1    A    2 
2    E    2 
2    F    2 
3    H    3
 
Share this answer
 
v3
Comments
George Swan 20-May-17 4:35am    
An excellent well-constructed solution, +5
Maciej Los 21-May-17 7:01am    
Thank you, George.
[no name] 20-May-17 5:20am    
Wow a 5
Maciej Los 21-May-17 7:01am    
Thank you, Bruno.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900