How do I cast a Listlt;Tgt; effectively?(我如何投射 Listlt;Tgt;有效地?)
问题描述
我有一个
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
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<T>有效地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何投射 List<T>有效地?
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
