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

How Can I Efficiently Cast a List to a List in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 11:33:39610browse

How Can I Efficiently Cast a List to a List in C#?

Casting from a List to a List with Less Code

The conversion from a list of items of type X to type Y, where X can be cast to Y, is possible one item at a time:

List<Y> ListOfY = new List<Y>();

foreach(X x in ListOfX)
    ListOfY.Add((Y)x);

However, a more concise method exists for casting the entire list at once:

List<Y> listOfY = listOfX.Cast<Y>().ToList();

Considerations for Using This Method:

  • It does not cast the list itself but rather each item within it.
  • A new List is created through the call to ToList().
  • It relies on the System.Linq namespace for its functionality.
  • It only supports implicit cast operators, excluding custom ones and those with explicit operators in Framework 4.0.

The above is the detailed content of How Can I Efficiently Cast 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