I am trying to run this query but it gives me exception.
"At least one object must implement IComparable."
I don't want to order/distinct by my custom object but just by a string (v.Venue). However the similar query with a custom object (instead of string), that doesn't implement IComparable, works fine.
here is my query:
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))
);
EventsList is an ObservableCollection<EventSchedules>
Also, I tried breaking the entire query into pieces, but it fails only for this last query:
Select((v, index) => new KeyValuePair<int, String>(index, v.Venue))
EventList object has to implement IComparable in order to execute Distinct() and OrderBy() functions. Linq needs to know how to compare instances of EventList in order to sort them and remove duplicates.
Comment answer: You can order by and do distinct by p.Venue. I.e.:
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))
);
Or you can implement a custom comparer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With