Reputation: 6622
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))
Upvotes: 3
Views: 318
Reputation: 6622
I solved it after analyzing my query, I didn't want to sort on my Custom Object (EventSchedule) as others suggested. What I wanted to order & distinct is an string. So I rearranged my query as:
new ObservableCollection<KeyValuePair<int, string>>(
EventsList.Where(p => !string.IsNullOrEmpty(p.Venue))
.Select(p => p.Venue) //added this
.Distinct()
.OrderBy(i => i)
.Select((v, index) => new KeyValuePair<int, String>(index, v))
);
Upvotes: 0
Reputation: 8280
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.
Upvotes: 5
Reputation: 555
As per LINQ basics ,
If you are using EventList you have to implement Icomparable to use distinct and Orderby.
I am sure your Query is breaking at OrderbY line but it is shows at Next Line
Upvotes: 0