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.
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.
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);
Try to use HashTable
instead of List
Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen"
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();
}