过滤重复了IEnumerable的 [英] Filtering duplicates out of an IEnumerable

查看:100
本文介绍了过滤重复了IEnumerable的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

class MyObj {
    int Id;
    string Name;
    string Location;
}

IEnumerable<MyObj> list;



我想列表转换为这样的字典:

I want to convert list to a dictionary like this:

list.ToDictionary(x => x.Name);



但它告诉我,我有重复键。我怎么能只保留第一项为每个键?

but it tells me I have duplicate keys. How can I keep only the first item for each key?

推荐答案

我想最简单的方法是将GROUP BY键,并采取每个组的第一个元素:

I suppose the easiest way would be to group by key and take the first element of each group:

list.GroupBy(x => x.name).Select(g => g.First()).ToDictionary(x => x.name);



或者,如果你的对象,你可以使用鲜明实施 IEquatable 来者皆它们之间比较:

Or you could use Distinct if your objects implement IEquatable to compare between themselves by key:

// I'll just randomly call your object Person for this example.
class Person : IEquatable<Person> 
{
    public string Name { get; set; }

    public bool Equals(Person other)
    {
        if (other == null)
            return false;

        return Name == other.Name;
    }

    public override bool Equals(object obj)
    {
        return base.Equals(obj as Person);
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}

...

list.Distinct().ToDictionary(x => x.Name);



或者,如果你不想做(也许是因为你通常要比较的平等以不同的方式,所以等于已在使用),你可以做的自定义实现的IEqualityComparer 只是这种情况下:

Or if you don't want to do that (maybe because you normally want to compare for equality in a different way, so Equals is already in use) you could make a custom implementation of IEqualityComparer just for this case:

class PersonComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        if (x == null)
            return y == null;

        if (y == null)
            return false;

        return x.Name == y.Name;
    }

    public int GetHashCode(Person obj)
    {
        return obj.Name.GetHashCode();
    }
}

...

list.Distinct(new PersonComparer()).ToDictionary(x => x.Name);

这篇关于过滤重复了IEnumerable的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆