C# 在 List<T> 和 IEnumerable<T> 之间自由转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/472669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:46:47  来源:igfitidea点击:

Freely convert between List<T> and IEnumerable<T>

c#linqlistienumerable

提问by TK.

How can I convert a List<MyObject>to an IEnumerable<MyObject>and then back again?

如何将 a 转换List<MyObject>为 anIEnumerable<MyObject>然后再返回?

I want to do this in order to run a series of LINQ statements on the List, e. g. Sort()

我想这样做是为了在列表上运行一系列 LINQ 语句,例如 Sort()

采纳答案by Tamas Czinege

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

回答by Marc Gravell

Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existinglist - list.OrderBy(...).ToList()will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

旁白:请注意,标准 LINQ 运算符(按照前面的示例)不会更改现有列表 -list.OrderBy(...).ToList()将根据重新排序的序列创建一个新列表。但是,创建一个扩展方法非常容易,它允许您将 lambdas 与List<T>.Sort以下内容一起使用:

static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}

Then you can use:

然后你可以使用:

list.Sort(x=>x.SomeProp); // etc

This updates the existinglist in the same way that List<T>.Sortusually does.

这以与通常相同的方式更新现有列表List<T>.Sort

回答by Frederik Gheysels

A List<T>is an IEnumerable<T>, so actually, there's no need to 'convert' a List<T>to an IEnumerable<T>. Since a List<T>is an IEnumerable<T>, you can simply assign a List<T>to a variable of type IEnumerable<T>.

AList<T>是 an IEnumerable<T>,所以实际上,没有必要将 a '转换'List<T>为 an IEnumerable<T>。由于 aList<T>是 an IEnumerable<T>,您可以简单地将 a 分配给List<T>类型为 的变量IEnumerable<T>

The other way around, not every IEnumerable<T>is a List<T>offcourse, so then you'll have to call the ToList()member method of the IEnumerable<T>.

周围的其他方法,并不是每IEnumerable<T>一个List<T>offcourse,所以那么你就必须要调用ToList()的成员方法IEnumerable<T>

回答by Dan Berindei

A List<T>is already an IEnumerable<T>, so you can run LINQ statements directly on your List<T>variable.

AList<T>已经是IEnumerable<T>,因此您可以直接在List<T>变量上运行 LINQ 语句。

If you don't see the LINQ extension methods like OrderBy()I'm guessing it's because you don't have a using System.Linqdirective in your source file.

如果您没有看到 LINQ 扩展方法,OrderBy()我猜是因为您using System.Linq的源文件中没有指令。

You do need to convert the LINQ expression result back to a List<T>explicitly, though:

不过,您确实需要将 LINQ 表达式结果List<T>显式转换回 a :

List<Customer> list = ...
list = list.OrderBy(customer => customer.Name).ToList()

回答by TamusJRoyce

To prevent duplication in memory, resharper is suggesting this:

为了防止内存重复,resharper 建议这样做:

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myList as List<string>() ?? myEnumerable.ToList();

.ToList() returns a new immutable list. So changes to listAgain does not effect myList in @Tamas Czinege answer. This is correct in most instances for least two reasons: This helps prevent changes in one area effecting the other area (loose coupling), and it is very readable, since we shouldn't be designing code with compiler concerns.

.ToList() 返回一个新的不可变列表。因此,对 listAgain 的更改不会影响 @Tamas Czinege 答案中的 myList。在大多数情况下这是正确的,至少有两个原因:这有助于防止一个区域的更改影响另一个区域(松散耦合),并且它非常易读,因为我们不应该考虑编译器来设计代码。

But there are certain instances, like being in a tight loop or working on an embedded or low memory system, where compiler considerations should be taken into consideration.

但是在某些情况下,例如处于紧密循环中或在嵌入式或低内存系统上工作,应考虑编译器方面的考虑。

回答by Nipuna

Converting List<T>to IEnumerable<T>

转换List<T>IEnumerable<T>

List<T>implements IEnumerable<T>(and many other such as IList<T>, ICollection<T>) therefore there is no need to convert a List back to IEnumerable since it already a IEnumerable<T>.

List<T>实现IEnumerable<T>(以及许多其他诸如IList<T>, ICollection<T>),因此无需将 List 转换回 IEnumerable,因为它已经是IEnumerable<T>.

Example:

例子:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Person person1 = new Person() { Id = 1, Name = "Person 1" };
Person person2 = new Person() { Id = 2, Name = "Person 2" };
Person person3 = new Person() { Id = 3, Name = "Person 3" };

List<Person> people = new List<Person>() { person1, person2, person3 };

//Converting to an IEnumerable
IEnumerable<Person> IEnumerableList = people;

You can also use Enumerable.AsEnumerable()method

您也可以使用Enumerable.AsEnumerable()方法

IEnumerable<Person> iPersonList = people.AsEnumerable();


Converting IEnumerable<T>to List<T>

转换IEnumerable<T>List<T>

IEnumerable<Person> OriginallyIEnumerable = new List<Person>() { person1, person2 };
List<Person> convertToList = OriginallyIEnumerable.ToList();

This is useful in Entity Framework.

这在Entity Framework 中很有用。