C# 如何将一系列项目添加到 IList 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13158121/
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
how to add a range of items to the IList variable
提问by mohsen dorparasti
there is no AddRange()method for IList<T>.
没有AddRange()方法IList<T>。
How can I add a list of items to a IList<T>without iterating through items and using Add()method ?
如何在IList<T>不迭代项目和使用Add()方法的情况下将项目列表添加到 a ?
采纳答案by Oded
AddRangeis defined on List<T>, not the interface.
AddRange在 上定义List<T>,而不是在接口上。
You can declare the variable as List<T>instead of IList<T>or cast it to List<T>in order to gain access to AddRange.
您可以将变量声明为List<T>代替IList<T>或将其强制转换List<T>为以获取对AddRange.
((List<myType>)myIList).AddRange(anotherList);
回答by Rayshawn
You could do something like this:
你可以这样做:
IList<string> oIList1 = new List<string>{"1","2","3"};
IList<string> oIList2 = new List<string>{"4","5","6"};
IList<string> oIList3 = oIList1.Concat(oIList2).ToList();
So, basically you would use the Concat()extension and ToList()to get a similar functionality as AddRange().
所以,基本上你会使用Concat()扩展并ToList()获得与AddRange().
回答by bashis
You could also write an extension method like this:
您还可以编写这样的扩展方法:
internal static class EnumerableHelpers
{
public static void AddRange<T>(this IList<T> collection, IEnumerable<T> items)
{
foreach (var item in items)
{
collection.Add(item);
}
}
}
Usage:
用法:
IList<int> collection = new int[10]; //Or any other IList
var items = new[] {1, 4, 5, 6, 7};
collection.AddRange(items);
Which is still iterating over items, but you don't have to write the iteration or cast every time you call it.
它仍在迭代项目,但您不必每次调用它时都编写迭代或强制转换。
回答by BlackHymanetMack
If you look at the c# source code for List, I think List.AddRange() has optimizations that a simple loop doesn't address. So, an extension method should simply check to see if the IList is a List, and if so use its native AddRange().
如果您查看List的c# 源代码,我认为 List.AddRange() 具有简单循环无法解决的优化。因此,扩展方法应该简单地检查 IList 是否为 List,如果是,则使用其原生 AddRange()。
Poking around the source code you see the .NET folks do similar things in their own Linq extensions for things like .ToList() (if it is a list, cast it...otherwise create it).
仔细查看源代码,您会看到 .NET 人员在他们自己的 Linq 扩展中为 .ToList() 之类的东西做类似的事情(如果它是一个列表,则将其转换...否则创建它)。
public static class IListExtension
{
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items)
{
if (list == null) throw new ArgumentNullException(nameof(list));
if (items == null) throw new ArgumentNullException(nameof(items));
if (list is List<T> asList)
{
asList.AddRange(items);
}
else
{
foreach (var item in items)
{
list.Add(item);
}
}
}
}
回答by Siva Ragu
var var1 = output.listDepartment1
var var2 = output.listDepartment2
var1.AddRange(var2);
var list = var1;

