我怎么投了名单< T>有效? [英] How do I cast a List<T> effectively?

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

问题描述

我有一个

 列表< InputField>

但我需要一个

 列表< IDataField>

有没有办法在C#中投呢?或使用LINQ获得同样的结果?

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

 接口IDataField {}
类InputField:IDataField {}
类PurchaseField:IDataField {}

该列表来自一个LINQ到SQL查询:

 列表< InputField>名单=(从我....我选择).ToList();


解决方案

这两个.OfType< T>和.Cast< T>将返回T的列表,但是这两种方法的含义是不同的。

list.OfType的过滤器原始列表,并返回一个是类型T的所有项目,并跳过属于该类型的不是人。

list.Cast 的演员在原始列表中的所有项目类型T,并抛出一个例外不能被强制转换为这种类型的项目。

在你的情况都将产生相同的结果,但使用.Cast会更清楚地表达你的意图了很多,所以我会建议使用。

 列表< InputField>名单=(从我....我选择).Cast< IDataField> .ToList();

I have a

List<InputField>

but I need a

List<IDataField>

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 { }

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

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

解决方案

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

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 casts all items in the original list to type T, and throws an exception for items which cannot be cast to that type.

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();

这篇关于我怎么投了名单&LT; T&GT;有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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