开发者

Ordering lists within a list in C#

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..??


It strikes me that your model is a bit messed up, but if you're sure that:

  • A person will have at least one site
  • All the sites for a particular person will be for the same organization

you can use:

var sorted = people.OrderBy(p => p.Sites.First().Organization)
                   .ThenBy(p => p.LastName)
                   .ThenBy(p => p.FirstName);


people.SelectMany(p => p.Sites).OrderBy(s => s.Organisation.Name).ThenBy(s => s.Organisation.Contact.Surname).ThenBy(s => s.Organisation.Contact.FirstName);


Linq supports an order by clause. Check out this MSDN link

http://msdn.microsoft.com/en-us/library/bb383982.aspx

Example

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);    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜