【问题标题】:How I can convert System.Collection.IEnumerable to List<T> in c#? [duplicate]如何在 c# 中将 System.Collection.IEnumerable 转换为 List<T>? [复制]
【发布时间】:2017-02-24 05:48:02
【问题描述】:

如何将System.Collection.IEnumerable 转换为 c# 中的列表? 实际上,我正在执行一个存储过程,它在System.Collection.IEnumerable 中为我提供了ResultSets,我想将该结果集转换为c# List&lt;User&gt;

注意我不想使用任何循环。有没有一种类型转换的方法!

【问题讨论】:

  • 不能ToList() 做吗?
  • @CircleHsiao 这不是重复的。请注意作者在这里要求 IEnumerable 而不是 IEnumerable
  • @CircleHsiao 这不是重复的,因为您的问题提到了 IEnumerable 但作者的意思是 IEnumerable。

标签: c# sql ado.net


【解决方案1】:

您可以使用以下内容:

IEnumerable myEnumerable = GetUser();
List<User> myList = myEnumerable.Cast<User>().ToList();

正如 Lasse V. Karlsen 在他的评论中建议的那样,您也可以使用 Cast&lt;User&gt; 而不是 OfType&lt;User&gt;();

如果默认情况下您的 IEnumerable 是通用的,我不认为这是因为您的命名空间存在问题:System.Collection.IEnumerable 您可以轻松使用:

IEnumerable<User> myEnumerable = GetUser();
List<User> myList = myEnumerable.ToList();

【讨论】:

  • 或者他可以使用OfType
  • @LasseV.Karlsen 感谢您的建议,我更新了我的答案。
【解决方案2】:

你应该可以只使用 Linq 的 ToList() 方法。

List<string> collection = myEnumCollection.ToList();

【讨论】:

  • 这不起作用,因为 OP 要求 System.Collection.IEnumerable 而不是使用 System.Collections.Generic.IEnumerable
猜你喜欢
  • 2015-09-12
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多