0

I have a list of the object where Parent ID is there for that item. How to check for the list of items whether the same parent is available more than once in the list.

For example.

Public Class Cars
{
  private int CarId {get; set;}
  private int CarParentId { get; set;}
  Private int CarName { get; set;}
}

List<Cars> Cars = new List<Cars>()
Cars.Add(Some Values)

How to check whether the Same parent is available more than once in the list.

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Samaritan_Learner
  • 547
  • 1
  • 4
  • 26
  • Please comment me if the question is just duplicate, I am ready to delete it. I have searched for more than 15-20 minutes and then I posted here. – Samaritan_Learner May 18 '20 at 16:52
  • A bit of a guess but does [this](https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property) help? It might be a duplicate but I'm not sure I understand your question correctly – Joelius May 18 '20 at 17:15
  • There are a few ways to check if the CarParentId appears multiple times in the list. What are you trying to achieve? Are you trying to count them for some other purpose (use .Count() as suggested by Prasad) or are you just trying to check if there are duplicates (use .Any() also in Linq)? Are you trying to stop duplicates from being added? More info needed. – sr28 May 18 '20 at 19:50

2 Answers2

1

You can use .Count(),

using System.Linq;
...

var parentId = 123;
if(Cars.Count(x => x.CarParentId == parentId) > 1)
{
   //There are more than 1 cars with 123 as a parentId
}
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
1

"How to check whether the Same parent is available more than once in the list."

It gives you multiple CarParentId list.

Cars.GroupBy(x => x.CarParentId).Where(x => x.Count() > 1).Select(x => x.Key);
anilcemsimsek
  • 803
  • 10
  • 21