EN VI

C# - How to cast list of object into derived collection class object?

2024-03-14 01:30:06
C# - How to cast list of object into derived collection class object

How can i cast them after apply linq to CollectionOfA object:

CollectionOfA obj = GetDataFromService();
obj= obj.OrderBy(x=>x.Name).ToList(); 

Here it gives compiler error cannot convert to implicit type on above line from Generic List to CollectionOfA.

Here is my classes:

public class A{
public int Id {get;set;}
public string Name {get;set;}
}

public class CollectionOfA: List<A>{
}

Solution:

ToList() will not create a CollectionOfA. You could assign a CollectionOfA (i.e., the more derived class) to a List<A> (the less derived class) but not the other way round.

The way to go is to use the Sort method inherited from List<T>

obj.Sort((a, b) => a.Name.CompareTo(b.Name));

This also has the advantage to not allocate a new collection but to do an in-place sort.


Another option is to add a constructor to your collection class by inheriting the corresponding one form List<T>:

public class CollectionOfA : List<A>
{
    public CollectionOfA()
    {
    }

    public CollectionOfA(IEnumerable<A> collection) : base(collection)
    {
    }
}

Note that we also must add the default constructor to not break existing code.

We can the use it like this:

obj = new CollectionOfA(obj.OrderBy(x => x.Name).ThenBy(x => x.Id));
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login