How to remove sublists with lowest counts and keep the one with the highest count from the main list?
-
15-10-2019 - |
Question
I have a list of sublists which is as List<List<nodes>>
. I have stored some lists in the List of lists that now i refer to as the main list. Now i have to compare the counts of the elements in the sublists, that is lists that are stored in main list. I need to keep only that sublist which has the highest count amongst all the sublists and remove the remaining sublists. How to do that?
Solution
List<List<Foo>> mainList = ...
// Find count of biggest sub-list.
int maxCount = mainList.Max(list => list.Count);
// Remove all other sub-lists.
mainlist.RemoveAll(list => list.Count != maxCount);
Do note that if more there are multiple sub-lists with maximum-count, all of them will be retained.
If you don't want this, you could arbitrarily choose one of them to retain:
if(mainlist.Count != 1)
mainList.RemoveRange(1, mainList.Count - 1);
If you don't care about performance, and you don't mind reassigning the variable, you could do:
mainList = mainList.OrderByDescending(list => list.Count)
.Take(1)
.ToList();
EDIT:
In .NET 2.0, you could do something like:
public static void KeepBiggestSubList<T>(List<List<T>> mainList)
{
if (mainList == null)
throw new ArgumentNullException("mainList");
if (mainList.Count == 0)
return;
List<T> maxList = mainList[0];
foreach (List<T> list in mainList)
{
if (list.Count > maxList.Count)
maxList = list;
}
mainList.Clear();
mainList.Add(maxList);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow