C# 将对象集合添加到另一个对象集合而不进行迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9492404/
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-09 07:37:13  来源:igfitidea点击:

Add Object Collection to another Object Collection without iterating

c#.netlinqentity-framework

提问by Deepak

I have a collection of objects objcol1(example Collection of cities in a state) and another object collection objcol2(example collection of cities in a country). Now I am querying for objcol1 and I want to add it to objcol2. I can do this by iterating through objcol1 and adding one by one to objcol2 but can I directly add objcol1 to objcol2 like objcol2.add(objcol1);

我有一个对象集合 objcol1(一个州的城市的示例集合)和另一个对象集合 objcol2(一个国家的城市的示例集合)。现在我正在查询 objcol1,我想将它添加到 objcol2。我可以通过遍历 objcol1 并一个一个地添加到 objcol2 来做到这一点,但是我可以像objcol2.add(objcol1)一样直接将 objcol1 添加到 objcol2

Can anyone tell me whether it is possible without iterating? If yes please explain me the process

谁能告诉我不迭代是否可行?如果是,请向我解释过程

采纳答案by M.Babcock

You could use the Enumerable.Concatextension method:

您可以使用Enumerable.Concat扩展方法:

objcol1 = objcol1.Concat(objcol2)

I'm sure under the covers somewhere it actually iterates, but you won't need to write the code to do it.

我确定它实际上在某个地方进行了迭代,但您不需要编写代码来执行它。

NOTE: This will only work if your Cityobjects are the same, alternatively you could use Selectto map the objects.

注意:这仅在您的City对象相同时才有效,或者您可以Select用来映射对象。

回答by Craig Wilson

Yes, it is possible depending upon your use case. If you don't care what the "collection" type is, then you can use the linq Concat command to create a new enumerable that, when iterated, will include items from both collections.

是的,这取决于您的用例。如果您不关心“集合”类型是什么,那么您可以使用 linq Concat 命令来创建一个新的枚举,当迭代时,它将包含来自两个集合的项目。

var collection1 = new List<int> { 1, 2, 3 };
var collection2 = new [] { 4, 5, 6};

var concatenated = collection1.Concat(collection2);

If, on the other hand, you need to actually insert the items into the existing collection, you'll need to iterate.

另一方面,如果您需要将项目实际插入到现有集合中,则需要进行迭代。

回答by Faust

Actually, you don't need a new var:

实际上,您不需要新的 var:

collection1.AddRange(collection2);

回答by Tx3

You can also use AddRangeof the List. See documentationfor more information.

你也可以使用AddRangeList。有关更多信息,请参阅文档

var a = new List<string> { "1", "2" };
var b = new List<string> { "3", "4" };
a.AddRange(b);

// a would contain "1", "2", "3" and "4"