Sort a field of each object in a list with LINQ

后端 未结 3 1791
轻奢々
轻奢々 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:32
    ((List<sample>)sam).ForEach(s => s.list.Sort());
    
    0 讨论(0)
  • 2021-01-17 08:34

    Try,

     sam.All(p => { p.list.Sort(); return true; });
    
    0 讨论(0)
  • 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<int>{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<int>(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.

    0 讨论(0)
提交回复
热议问题