2

want to check if list contains same items

var listme = new List<string>();
listme.Add("list1"); 
listme.Add("list1");

And want to count the number of same items and copy it and then remove it from list.

3 Answers3

4

You can do it in a single LINQ statement with GroupBy and ToDictionary:

var dupCounts = listme
    .GroupBy(s => s)
    .Where(g => g.Count() > 1) // Keep only groups with duplicates
    .ToDictionary(g => g.Key, g => g.Count());

This produces a Dictionary<string,int> where each item from the list is mapped to its corresponding count from the original list. Now you can remove all duplicates from the original list:

listme.RemoveAll(dupCounts.Keys);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Try to use HashTable instead of List

Hashtable hashtable = new Hashtable();
            hashtable[1] = "One";
            hashtable[2] = "Two";
            hashtable[13] = "Thirteen"
Husni Salax
  • 1,968
  • 1
  • 19
  • 29
0

You can use linq, see below:

public static void Main()
{
    var listme = new List<string> {"A", "A", "B", "C", "C"};

    // count
    var countDict = listme.GroupBy(i => i)
        .ToDictionary(i => i.Key, i => i.Count());

    foreach (var kv in countDict)
    {
        Console.WriteLine($"{kv.Key}: {kv.Value}");
    }

    // remove
    listme.RemoveAll(s => s == "A");
    foreach (string s in listme)
    {
        Console.WriteLine(s);
    }

    Console.ReadLine();
}
Student222
  • 3,021
  • 2
  • 19
  • 24