I have a class called "Orders" that has the property of "City" among others. I am trying to write a LINQ statement that will get all the distinct cities from a list of orders and return them as a list of strings.
Here is what I have now.
public List<string> GetOrderCities(List<Order> orders)
{
IEnumerable<string> cities= from o in orders
select o.City.Distinct().ToString();
return cities.ToList();
}
However, when I run this by passing it a list of orders, I don't seem to be getting anything back. The list is empty that it is returning. The orders I am passing it do all have City values. Am I just flat out doing this wrong? Thanks!
LINQ Distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. LINQ Distinct is an operator which comes under Set Operator.
LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.
distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table). I know writing basic query using distinct as followed: var query = (from r in table1 orderby r. Text select r).
You're miscalling the Distinct()
method.
Change it to
return orders.Select(o => o.City).Distinct().ToList();
Or, using query comprehension syntax:
return (from o in orders
select o.City
).Distinct().ToList();
(Note parentheses)
Your code calls Distinct
on the City
property itself, which is a string.
Since the String
class implements IEnumerable<char>
, this method returns an IEnumerable<char>
containing all of the unique characters in the string.
You then call ToString()
on this enumerable (which is a compiler-generated iterator type from System.Core.dll), which always returns System.Linq.Enumerable+d__81`1[System.Char]
.
Instead, you need to call .Distinct()
on the IEnumerable<string>
returned by the Select
method.
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