I am using Linq to get only unique member of a select List item. How do I return a this list…
What I have now is
var queryResult = PatientList.Select(c => c).Distinct();
PatientList = (List<SelectListItem>)queryResult;
I am getting a cast error on the second line. What should an enterprising young developer do?
Try
You version uses casting, which is impossible in this case, as the query result is not a list.
ToListconstructs a new list, basing on the enumerable against which it is called. It does something like this:You must be sure, obviously, that
PatientListelements are of typeSelectListItemand be aware thatDistinct()will return the different OBJECTS, but not items with different fields. I.e., if inPatientListyou have two independently constructed items with equalSelected,TextandValueproperties, you will still have two as a result of theDistinct()call.Additionally, what is the reason to use
Select(c => c)? It effectively does noting.