C# LINQ 选择多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15674196/
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
LINQ Select Multiple value
提问by abc cba
My code is as below , the usage of this code is to merge 2 list together. and replace its value from one to another.
我的代码如下,这段代码的用途是将2个列表合并在一起。并将其值从一个替换为另一个。
(from L1 in List1
join L2 in List2
on L1.itemID equals L2.itemID
select L1.itemName= L2.itemName).ToArray();
The code above work perfectly but only for selecting a single attribute which is itemName , how should I write the code if I want to select more than 1 value ,
上面的代码工作完美,但仅用于选择 itemName 的单个属性,如果我想选择超过 1 个值,我应该如何编写代码,
e.g
例如
(from L1 in List1
join L2 in List2
on L1.itemID equals L2.itemID
select {L1.itemName= L2.itemName , L1.ItemQuantity = L2.Quatity}).ToArray();
采纳答案by jacob aloysious
You could directly use the property names, as shown below.
您可以直接使用属性名称,如下所示。
The returning array would contain objects with the same Properties itemID
and itemName
.
返回的数组将包含具有相同 PropertiesitemID
和 的对象itemName
。
var outp = (from L1 in List1
join L2 in List2
on L1.itemID equals L2.itemID
select new { L1.itemID, L2.itemName }).ToArray();
Sample Output:
示例输出:
回答by TGH
(from L1 in List1
join L2 in List2
on L1.itemID equals L2.itemID
select new{Prop1 = L1.SomePropery,Prop2 = L1.SomeOtherProperty).ToArray();
OR unnamed -using default names
或未命名 - 使用默认名称
(from L1 in List1
join L2 in List2
on L1.itemID equals L2.itemID
select new{L1.SomePropery,L1.SomeOtherProperty).ToArray();
回答by Jeff Mercado
If you wish to merge the two objects, you should first match corresponding objects to be joined, then go through the matched objects and copy the properties over. Don't use a LINQ query like that, that's not what it was designed for.
如果你想合并两个对象,你应该先匹配要连接的对应对象,然后遍历匹配的对象并复制属性。不要使用这样的 LINQ 查询,这不是它的设计目的。
// pair off all the items in both lists
var matches =
from item1 in List1
join item2 in List2 on item1.ItemID equals item2.ItemID
select new { item1, item2 };
foreach (var match in matches)
{
// copy the properties over for each corresponding match
match.item1.ItemName = match.item2.ItemName;
match.item1.ItemQuantity = match.item2.Quantity;
}