Sort a field of each object in a list with LINQ

后端 未结 3 1792
轻奢々
轻奢々 2021-01-17 08:08

Is is possible to sort an item in a IEnumerable list using LINQ?

For example:

        IEnumerable sam = new List()
               


        
3条回答
  •  一整个雨季
    2021-01-17 08:42

    The general shape for LINQ is that it does not change the original data. For example, if we have a list

    var ints = new  List{5,6,1};
    

    and use linq to 'sort it'

    var sorted = ints.OrderBy();
    

    we end up with two lists

    ints => { 5,6,1}
    sorted => {1,5,6}
    

    In your above example, it depends on what you want the output to be

    If you want a new list of samples where the list is sorted then you can use

    var newSampleList = samples.Select( sam => new Sample { 
                                                     id = sam.id, 
                                                     name = sam.name, 
                                                     list = new List(sam.list.OrderBy())
                                       });
    

    If you do not want to create a new list but want to sort the values in place it is not really what LINQ is intended for but it can be done using something like AVD's answer to execute functionality on each member (in this case call Sort on the list).

    NOTE: This will only work if sample.list is defined as a List() as Sort() only exists on List<>. If defined as IList or IEnumerable it will not work.

提交回复
热议问题