HOW TO SORT OBJECT IN LIST AND UPDATE OBJECT USING LINQ?

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C#
 956  View(s)
Ratings:
Rate this:
I am writing a function to sort a List using a property inside the list. I need to sort the MyClass object obj using the property Age of the list AnimalList and assign the sorted list back to obj. After performing the function obj should get updated with the new sorted object. My list value has got the sorted list now. I need to update that to obj.

I have tried many possibilities but couldn't bind it the list to the object.

public void SortBlocks(MyClass obj)

{

      List<Animal> value = obj.AnimalList;

      value = value.OrderBy(val => val.Age).ToList();

}

 

public interface MyClass

{

     List<Animal> AnimalList { get; set; }

}

public class Animal

{

     public string color { get; set; }

     public uint Age { get; set; }

}

  1. Ashish Pandey

    Post:128

    Points:898
    Re: How to sort object in list and update object using linq?

    You mean something like this?

    var list = new List<Person>
    {
        new Person("me", 10),
        new Person("you", 5),
        new Person("dad", 30),
    };
    
    var result = list.OrderBy(x => x.Age);
    
    foreach (var entry in result)
        Console.WriteLine(entry.Name + ": " + entry.Age);

    where the Person object is defined as

    class Person
    {
        public string Name { get; set; }
        public int Age {get;set;}
    
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    this will print:

    you: 5
    me: 10
    dad: 30

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!