尝试将IList转换为List以便AddRange

我有一个IList 。 我尝试调用ToList ,然后调用AddRange

但是, ToList()覆盖所有结果。 怎么会?

 private void AddAliasesThatContainsCtid(string ctid, IList results) { ... foreach (var alias in aliases) { var aliasId = "@" + alias; results.ToList().AddRange(mMaMDBEntities.MamConfigurationToCTIDs_V1.Where(item => item.CTID == aliasId) .Select(item => item.MamConfiguration_V1) .ToList()); } } 

.ToList()不会将IEnumerable转换为List ,它会创建并返回一个填充了枚举值的新列表。

所以你的result.ToList()将创建一个新的列表并用一些数据填充它。 但它不会更改result参数引用的对象的内容。

为了实际更改result参数的内容,您必须使用它的.Add方法,或者如果您的设计允许它将result类型更改为List<..>

您的代码是等效的:

 // Create new List by calling ToList() var anotherList = results.ToList(); anotherList.AddRange(...); 

因此,您实际上将项目添加到anotherList列表,而不是result列表。

要获得正确的结果,有两种方法:

1:

results声明为out并返回:

 results = anotherList; 

要么:

 results = results.ToList().AddRange(...) 

2:

使用IList支持的Add方法而不是AddRange

这很简单:

 public static class ListExtensions { public static IList AddRange(this IList list, IEnumerable range) { foreach (var r in range) { list.Add(r); } return list; } } 

虽然IList没有AddRange() ,但它确实Add() ,所以你可以IList编写一个扩展方法,让你可以为它添加一个范围。

如果你这样做,你的代码将成为:

 private void AddAliasesThatContainsCtid(string ctid, IList results) { ... results.AddRange(mMaMDBEntities.MamConfigurationToCTIDs_V1 .Where(item => item.CTID == aliasId) Select(item => item.MamConfiguration_V1)); } } 

可编译的示例实现:

 using System; using System.Collections.Generic; using System.Linq; namespace Demo { internal class Program { static void Main() { IList list = new List{"One", "Two", "Three"}; Print(list); Console.WriteLine("---------"); var someMultiplesOfThree = Enumerable.Range(0, 10).Where(n => (n%3 == 0)).Select(n => n.ToString()); list.AddRange(someMultiplesOfThree); // Using the extension method. // Now list has had some items added to it. Print(list); } static void Print(IEnumerable seq) { foreach (var item in seq) Console.WriteLine(item); } } // You need a static class to hold the extension method(s): public static class IListExt { // This is your extension method: public static IList AddRange(this IList @this, IEnumerable range) { foreach (var item in range) @this.Add(item); return @this; } } }