Reputation: 6216
I need a push in the right direction with regards to ordering data using Linq.
I've got a list of People objects in C#, which in turn, holds a list of Sites that the person may be associated with.
Those Site objects holds is an instance of an Organisation object, that the site is associated with (as an organisation may have many sites..)
Edit: A person will only belong to a single organisation in the list. (Thanks @jonskeet)
How do I order the list of people, using Linq (or Lamba) to show them in alphabetical order, by their Organisation, and then ordered by the Surname, Firstname of the contact..??
Upvotes: 1
Views: 195
Reputation: 211
Linq supports an order by clause. Check out this MSDN link
http://msdn.microsoft.com/en-us/library/bb383982.aspx
public class CityLookup
{ public string City { get; set; }
public string Country { get; set; }
}
List<CityLookup> citiesLkp =
new List<CityLookup>
{
new CityLookup{ City = "New Delhi", Country = "India" },
new CityLookup{ City = "Sydney", Country = "Australia" },
new CityLookup{ City = "Tokyo", Country = "Japan" },
new CityLookup{ City = "New York", Country = "USA" },
new CityLookup{ City = "Paris", Country = "France" },
new CityLookup{ City = "Barcelona", Country = "Spain" },
};
// Now sort the names based on city name
var myList = from c in citiesLkp orderby c.City select c;
foreach (var record in myList )
{
Console.WriteLine(record.City);
}
Upvotes: 0
Reputation: 1499770
It strikes me that your model is a bit messed up, but if you're sure that:
you can use:
var sorted = people.OrderBy(p => p.Sites.First().Organization)
.ThenBy(p => p.LastName)
.ThenBy(p => p.FirstName);
Upvotes: 3
Reputation: 20451
people.SelectMany(p => p.Sites).OrderBy(s => s.Organisation.Name).ThenBy(s => s.Organisation.Contact.Surname).ThenBy(s => s.Organisation.Contact.FirstName);
Upvotes: 0