2

I have the following model class:

public class DuplicateTags
{
    public string VMName { set; get; }
    public string shortName { set; get; }
}

It is being populated as follow:

int tempindex = tempvmname.IndexOf('-');
duplicateTagsInDisplayName.Add(new DuplicateTags 
{ 
    VMName = tempvmname, 
    shortName = tempvmname.Substring(0, tempindex)
});

Now I want to display the list items that have duplicate shortName?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
John John
  • 1
  • 72
  • 238
  • 501

3 Answers3

5

You can use linq to get duplicate values

var duplicateShortNames = duplicateTagsInDisplayName
    .GroupBy(x => x.shortName) // items with same shorName are grouped to gether
    .Where(x => x.Count() > 1) // filter groups where they have more than one memeber
    .Select(x => x.Key) // select shortName from these groups
    .ToList(); // convert it to a list

then you can check if any of your items are in duplicates and display them

foreach (var item in duplicateTagsInDisplayName)
{
    if (duplicateShortNames.Contains(item.shortName))
        Console.WriteLine(item.VMName + item.shortName);
}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
2

First of all, there is no such thing as a "two dimensional list" in .Net. You have a list of objects of type DuplicateTags, where DuplicateTag is a class having 2 properties.

Now, to solve your problem, I would suggest you learn about LINQ.

Specifically, you can use GroupBy for this:

var groupedByShortName = duplicateTagsInDisplayName.GroupBy(x => x.shortName);
var duplicates = groupedByShortName.Where(item => item.Count() > 1);
foreach (var duplicate in duplicates)
{
    Console.WriteLine("{0} occurs {1} times", duplicate.Key, duplicate.Count);
    foreach (var item in duplicate)
    { 
        Console.WriteLine("   {0}", item.VMName);
    } 
}

Read more here: https://learn.microsoft.com/en-us/dotnet/csharp/linq/group-query-results

jeroenh
  • 26,362
  • 10
  • 73
  • 104
1

This should work:

var list = new []{ 
                new{ VMName = "a", shortName = "sn1" },
                new{ VMName = "a", shortName = "sn2" },
                new{ VMName = "b", shortName = "sn1" },
};

var groupedList = list.GroupBy(x => x.shortName)
                           .Select(x => 
                                        new{ 
                                             ShortName = x.Key, 
                                             Items = x,                                             
                                             Count = x.Count()
                                           }
                                  );

var onlyDuplicates = groupedList.Where(x => x.Count > 1);
Leo
  • 7,379
  • 6
  • 28
  • 44