Linq - 选择不同的值

时间:2013-09-12 07:45:41

标签: linq distinct

我在集合(List)中有以下对象

public class MyObject{

    string vendor;
    string unit;

    int unit123;
    AnotherObject unit456;
}

这可能很长且重复。

我想使用linq选择供应商和单位的不同值,并将其放在以下结构中

词典

有可能吗?

1 个答案:

答案 0 :(得分:11)

List<MyObject> l = new List<MyObject>();
//fill the list

Dictioonary<string,string> d = 
l
.Select
(
    x=>new
    {
        x.vendor,
        x.unit
    }
) //Get only the properties you care about.
.Distinct()
.ToDictionary
(
    x=>x.vendor,  //Key selector
    x=>x.unit     //Value selector
);
相关问题