Home > Backend Development > C++ > How Can I Convert a List to a List in C#?

How Can I Convert a List to a List in C#?

Linda Hamilton
Release: 2025-02-01 17:56:40
Original
397 people have browsed it

How Can I Convert a List to a List in C#?

C# List & LT; derived class & gt; converted to list & lt; base class & gt;

Inheritance in object -oriented programming allows derivatives to inherit the attributes and methods of its base class. However, sometimes it is not clear why this inheritance cannot be applied to generics like List.

Consider the following example:

In this code, the compiler error occurs because the list
interface A { }

class B : A { }

class C : B { }

class Test
{
    static void Main(string[] args)
    {
        A a = new C(); // 正确
        List<A> listOfA = new List<C>(); // 编译器错误
    }
}
Copy after login
cannot be implicitly converted into list

. Even if the class C inherits the interface A, the compiler cannot automatically convert the set of the derived class into a collection of its base class. In order to solve this problem, there are two ways:

Use convertall

Convertall method accepts a function as a parameter, and creates a new list by applying the function of the function to the source list. In this example, the function (x = & gt; (a) x) forcibly converts each element of list

into type A.
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
Copy after login

Use linq

LINQ's Cast () method allows you to convert one type of list into another list. By converting list <换> to list

and then converting it into list, you can create a collection of base class objects from a collection of the derived class object.
List<A> listOfA = new List<C>().Cast<A>().ToList();
Copy after login

The above is the detailed content of How Can I Convert a List to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template