我有IList
。我尝试拨打ToList
然后AddRange
。
但是,ToList()
会覆盖所有结果。怎么样?
private void AddAliasesThatContainsCtid(string ctid, IList<MamConfiguration_V1> 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());
}
}
答案 0 :(得分:5)
.ToList()
未将IEnumerable<T>
转换为List<T>
,它会创建并返回一个填充了可枚举值的新列表。
因此,您的result.ToList()
会创建一个新列表,并用一些数据填充它。但它不会更改result参数引用的对象的内容。
为了实际更改result
参数的内容,您必须使用.Add
方法,或者如果您的设计允许它将result
的类型更改为{{1 }}
答案 1 :(得分:2)
您的代码是等效的:
// Create new List by calling ToList()
var anotherList = results.ToList();
anotherList.AddRange(...);
因此,您实际上将项目添加到anotherList
,而不是result
列表中。
要获得正确的结果,有两种方法:
1:
将results
声明为out
并分配回来:
results = anotherList;
或者:
results = results.ToList().AddRange(...)
2:
使用Add
支持的IList
方法代替AddRange
答案 2 :(得分:1)
很简单:
public static class ListExtensions
{
public static IList<T> AddRange<T>(this IList<T> list, IEnumerable<T> range)
{
foreach (var r in range)
{
list.Add(r);
}
return list;
}
}
答案 3 :(得分:0)
虽然IList<T>
没有AddRange()
,但 却有Add()
,因此您可以编写扩展方法IList<T>
可以让你为它添加一个范围。
如果你这样做,你的代码就会变成:
private void AddAliasesThatContainsCtid(string ctid, IList<MamConfiguration_V1> 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<string> list = new List<string>{"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<T>(IEnumerable<T> 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<T> AddRange<T>(this IList<T> @this, IEnumerable<T> range)
{
foreach (var item in range)
@this.Add(item);
return @this;
}
}
}