【问题标题】:Remove duplicates by priority按优先级删除重复项
【发布时间】:2020-01-02 21:23:33
【问题描述】:

我有一个包含 id 和优先级的类的列表,如下所示:

此列表可以包含许多条目,其中一些可以是重复的。

如果列表中已经存在一个 id,我需要选择具有最高优先级的一个。在此示例中,前两个条目具有相同的 Id 但不同的优先级。所以优先级较低的必须从列表中排除。

有人对我有什么建议吗?将不胜感激。

【问题讨论】:

  • GroupBy Id, OrderBy Priority, Take One

标签: c# list linq duplicates


【解决方案1】:

有两种可能的方法:

class Program
{
    static void Main(string[] args)
    {
        Guid guid1 = Guid.NewGuid();
        List<Item> items = new List<Item>()
        {
            new Item
            {
                ID = guid1,
                Priority = 1
            },
            new Item
            {
                ID = guid1,
                Priority = 2
            },
            new Item
            {
                ID = guid1,
                Priority = 3
            },
            new Item
            {
                ID = Guid.NewGuid(),
                Priority = 1
            },
            new Item
            {
                ID = Guid.NewGuid(),
                Priority = 2
            },
            new Item
            {
                ID = Guid.NewGuid(),
                Priority = 3
            },
        };

        //IF YOU CAN CHANGE THE LIST
        items = items.GroupBy(x => x.ID).Select(x => x.OrderByDescending(y => y.Priority).First()).ToList();

        //IF YOU CAN CHANGE ONLY LIST ITEMS
        items.RemoveAll(z => items.GroupBy(x => x.ID).SelectMany(x => x.OrderByDescending(y => y.Priority).Skip(1).ToList()).ToList().Contains(z));
    }
}
public class Item
{
    public Guid ID { get; set; }
    public int Priority { get; set; }
}

【讨论】:

    【解决方案2】:

    您可以使用GroupBy,然后按优先级排序每个组并取第一个:

    var highPrioUniqueItemList = listmembers
        .GroupBy(x => x.id)
        .Select(g => g.OrderByDescending(x => x.priority).First())
        .ToList();
    

    【讨论】:

    • 非常感谢...我自己想出来的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多