Cendo Cendo - 6 months ago 33
C# Question

List of Objects. Find two Objects with same name

I have a List of Objects. The Objects have a name. How can i find two Objects in the List with same name.
Now i write all object names in a foreach loop into a list of strings and then check them.
is there a way to check same names of objects without write it into a list of strings to check this list?
so my code look like this:

List<string> objectnames = new List<string>();

foreach (object obj in DBobjects)

var doublicates = objectnames.GroupBy(x => x).Where(x => x.Count() > 1 ).Select(x => x.Key);

foreach(string name in doublicates)
//do something with each dublicate


You can directly use that on your original list:

var doublicates = DBobjects.GroupBy(x => x.name)
                           .Where(x => x.Count() > 1 )
                           .Select(x => new { Name = x.Key, objs = x.ToList() });

foreach(var duplicate in doublicates)
    // do something with duplicate.Name and duplicate.objs