Linq - 选择不同的值

Bic*_*ick 9 linq distinct

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

public class MyObject{

    string vendor;
    string unit;

    int unit123;
    AnotherObject unit456;
}
Run Code Online (Sandbox Code Playgroud)

这可能是漫长而重复的.

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

字典

可能吗?

Gia*_*los 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
);
Run Code Online (Sandbox Code Playgroud)