如何删除计数最低的子列表并从主列表中保留计数最高的子列表?

发布于 2024-10-10 09:53:59 字数 160 浏览 2 评论 0 原文

我有一个子列表列表,其形式为 List>。我在列表列表中存储了一些列表,现在我将其称为主列表。现在我必须比较子列表中元素的计数,即存储在主列表中的列表。我只需要保留所有子列表中计数最高的子列表,并删除剩余的子列表。怎么做呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最笨的告白 2024-10-17 09:53:59
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);

请注意,如果有多个具有最大计数的子列表,则所有子列表都将被保留。

如果您不希望这样,您可以任意选择其中之一来保留:

if(mainlist.Count != 1)
   mainList.RemoveRange(1, mainList.Count - 1);

如果您不关心性能,并且不介意重新分配变量,您可以这样做:

mainList = mainList.OrderByDescending(list => list.Count)
                   .Take(1)
                   .ToList();

编辑

在 .NET 2.0 中,您可以执行以下操作:

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);
}
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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文