我如何投射 List<T>有效地? [英] How do I cast a List<T> effectively?

查看:12
本文介绍了我如何投射 List<T>有效地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

List<InputField> 

但我需要一个

List<IDataField>  

有没有办法在 C# 中进行转换?或者使用 Linq 得到相同的结果?

Is there a way to cast this in c#? Or use Linq to get same result?

我有两个实现相同接口的类:

I have two classes that implement the same interface:

interface IDataField { }
class InputField : IDataField { }
class PurchaseField : IDataField { }

此列表来自 Linq-to-Sql 查询:

This List comes from a Linq-to-Sql query:

List<InputField> list = (from i .... select i).ToList();

推荐答案

Both .OfType和.Cast T会返回一个T的列表,但是两种方法的含义不同.

Both .OfType<T> and .Cast<T> will return a list of T, but the meaning of the two methods is different.

list.OfType() 过滤原始列表并返回所有属于 T 类型的项,并跳过不是该类型的项.

list.OfType() filters the original list and returns all items which are of type T, and skips the ones that are not of that type.

list.Cast() 原始列表中的所有项目转换为 T 类型,并为无法转换为该类型的项目抛出异常.

list.Cast() casts all items in the original list to type T, and throws an exception for items which cannot be cast to that type.

在您的情况下,两者都会给出相同的结果,但使用 .Cast() 会更清楚地传达您的意图,因此我建议使用它.

In your case both would give the same result, but using .Cast() would communicate your intent a lot more clearly, so I would recommend using that.

List<InputField> list = (from i .... select i).Cast<IDataField>().ToList();

这篇关于我如何投射 List&lt;T&gt;有效地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆