How can I sort a list of objects by a member of each object?

This question already has an answer here:

  • How to Sort a List<T> by a property in the object 19 answers

  • Pretty standard, simple linq.

    var candleList = candleList.Distinct().OrderBy(x => x.date).ToList();
    

    As Adam mentioned below, this will only remove duplicate instances within the list, not instances which all of the same property values.

    You can implement your own IEqualityComparer<Candle> as an option to get passed this. IEqualityComparer

    You may want to take a look at msdn, and read up on Linq and Enumerable Methods: MSDN - Enumerable Methods


    if you're using .NET 3.5 and above, you can use the OrderBy extension over IList like so:

    var orderList = candleList.OrderBy(s => s.date);
    

    Alternative you can use the SortBy

    var orderList = candleList.SortBy((x, y) => x.date.CompareTo(y.date) );
    

    To remove the duplicates you can do:

    var distinctList = orderList.GroupBy(x => x.date).Select(grp => grp.First());
    

    Finally to get the list again do

    var finalList = distinctList.ToList();
    

    In fluent way:

    List<candle> finalList = candleList.OrderBy(s => s.date).Distinct().ToList();
    

    By the way there quite a few other questions in stackoverflow that explains each of this questions, search them and you'll find other details.


    How can I then sort candleList by date?

    var orderedList = candleList.OrderBy(p=>p.date);
    

    Also, how can I remove all duplicate entries from candleList?

    You should tell us how you compare two candle objects. Assuming by date you can do:

    var uniqueList = candleList.GroupBy(p=>p.date).Where(p=>p.Count() == 1).ToList();
    

    Also, you can use Distinct() or intorduce a IEqualityComparer<candle> to this method to compare two candle objects and remove the duplicates.

    链接地址: http://www.djcxy.com/p/70942.html

    上一篇: 按属性名称排序列表<对象>

    下一篇: 我如何通过每个对象的成员对对象列表进行排序?