LINQ help distinct ()

I have a class called "Orders" that has the property "City" and others. I am trying to write a LINQ statement that will remove all the individual cities from the list of orders and return them to the list of lines.

Here is what I have.

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 him a list of orders, I seem to get nothing. The list is empty, which it returns. The orders that I transfer to him have all the meanings of the city. Am I just doing it wrong? Thank!

+5
source share
2 answers

You reject the method Distinct().

Change it to

return orders.Select(o => o.City).Distinct().ToList();

Or, using the syntax for understanding the request:

return (from o in orders
        select o.City
       ).Distinct().ToList();

(mark parentheses)

Distinct City, .
String IEnumerable<char>, IEnumerable<char>, .
ToString() ( , System.Core.dll), System.Linq.Enumerable+d__81`1[System.Char].

.Distinct() IEnumerable<string>, Select.

+12

, ... , Distinct() , List.

List<string> cities = (from o in orders
                       select o.City).Distinct().ToList();

            return cities;
+1

All Articles