我试图运行此查询,但它给了我例外.
"至少有一个对象必须实现IComparable."
我不想通过我的自定义对象来命令/区分,而只是通过字符串(v.Venue).但是,使用自定义对象(而不是字符串)的类似查询(未实现IComparable)工作正常.
这是我的查询:
new ObservableCollection<KeyValuePair<int, string>>(
EventsList.Where(p => !string.IsNullOrEmpty(p.Venue))
.Distinct()
.OrderBy(i => i)
.Select((v, index) => new KeyValuePair<int, String>(index, v.Venue))
);
Run Code Online (Sandbox Code Playgroud)
EventsList 是一个 ObservableCollection<EventSchedules>
此外,我尝试将整个查询分成几部分,但它只对最后一个查询失败:
Select((v, index) => new KeyValuePair<int, String>(index, v.Venue))
EventList对象必须实现IComparable才能执行Distinct()和OrderBy()运行.Linq需要知道如何比较实例EventList以便对它们进行排序并删除重复项.
评论答案:您可以通过p.Venue订购并做区别.即:
new ObservableCollection<KeyValuePair<int, string>>(
EventsList.Where(p => !string.IsNullOrEmpty(p.Venue))
.GroupBy(p => p.Venue)
.Select(grp => grp.First()) // These two lines are lambda way to say Distinct.
.OrderBy(p => p.Venue)
.Select((v, index) => new KeyValuePair<int, String>(index, v.Venue))
);
Run Code Online (Sandbox Code Playgroud)
或者您可以实现自定义比较器.