Sorting a list of classes using LINQ

I have List<MyClass>one and I want to sort it by DateTime CreateDateMyClass attribute .

Is this possible with LINQ?

thank

+3
source share
5 answers

You can list it in sorted order:

IEnumerable<MyClass> result = list.OrderBy(element => element.CreateDate);

You can also use ToList()to convert to a new list and reassign the original variable:

list = list.OrderBy(element => element.CreateDate).ToList();

This is not exactly the same as sorting the original list, because if someone else has a link to the old list, they will not see the new order. If you really want to sort the source list, you need to use a method List<T>.Sort.

+4
source

To sort an existing list:

list.Sort((x,y) => x.CreateDate.CompareTo(y.CreateDate));

Sort, :

list.Sort(x => x.CreateDate);

:

public static class ListExt {
    public static void Sort<TSource, TValue>(
            this List<TSource> list,
            Func<TSource, TValue> selector) {
        if (list == null) throw new ArgumentNullException("list");
        if (selector == null) throw new ArgumentNullException("selector");
        var comparer = Comparer<TValue>.Default;
        list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
    }
}
+5

:

using System.Collections.Generic;
using System.Linq;

namespace Demo
{ 
    public class Test
    {
        public void SortTest()
        {
            var myList = new List<Item> { new Item { Name = "Test", Id = 1, CreateDate = DateTime.Now.AddYears(-1) }, new Item { Name = "Other", Id = 1, CreateDate = DateTime.Now.AddYears(-2) } };
            var result = myList.OrderBy(x => x.CreateDate);
        }
    }

    public class Item
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public DateTime CreateDate { get; set; }
    }
}
+1

, .OrderBy() , IComparable .Sort()?

0
source
       class T  {
            public DateTime CreatedDate { get; set; }
        }

for use:

List<T> ts = new List<T>(); 
ts.Add(new T { CreatedDate = DateTime.Now }); 
ts.Add(new T { CreatedDate = DateTime.Now }); 
ts.Sort((x,y) => DateTime.Compare(x.CreatedDate, y.CreatedDate));

0
source

Source: https://habr.com/ru/post/1733090/


All Articles