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
Linda HamiltonOriginal
2025-02-01 17:56:40398browse

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
<code class="language-csharp">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>(); // 编译器错误
    }
}</code>
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.
<code class="language-csharp">List<A> listOfA = new List<C>().ConvertAll(x => (A)x);</code>

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.
<code class="language-csharp">List<A> listOfA = new List<C>().Cast<A>().ToList();</code>

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:
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