OHA
OHA

Reputation: 313

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)
{
    objectnames.Add(obj.name);
}

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

if(doublicates.Any())
{
    foreach(string name in doublicates)
    {
        //do something with each dublicate
    }
}

Upvotes: 3

Views: 3365

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43946

Why don't you just group your DBobjects:

var allDuplicates = DBobjects.GroupBy(o => o.name).Where(g => g.Count() > 1);

If you like you can convert this into a dictionary mapping from name to a list of the objects with that name:

var dict = allDuplicates.ToDictionary(g => g.Key, g => g.ToList());

Now for example you can list all duplicates:

foreach(string name in dict.Keys)
{
    Console.WriteLine($"There are {dict[name].Count} entries with name {name}:");
    foreach(var o in dict[name])
        Console.Write("    " + o.ToString());
}

Upvotes: 6

Zein Makki
Zein Makki

Reputation: 30052

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
}

Upvotes: 2

Related Questions