LINQ Select multiple values

My code is as below, using this code is to combine 2 lists together. and replace its value from one to another.

(from L1 in List1 join L2 in List2 on L1.itemID equals L2.itemID select L1.itemName= L2.itemName).ToArray(); 

The code above works fine, but only to select one attribute, which is itemName, how should I write the code if I want to select more than one value,

eg

 (from L1 in List1 join L2 in List2 on L1.itemID equals L2.itemID select {L1.itemName= L2.itemName , L1.ItemQuantity = L2.Quatity}).ToArray(); 
+6
source share
3 answers

You can directly use property names as shown below.

The returned array will contain objects with the same properties itemID and itemName .

  var outp = (from L1 in List1 join L2 in List2 on L1.itemID equals L2.itemID select new { L1.itemID, L2.itemName }).ToArray(); 

Output Example:

enter image description here

+12
source
 (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 - use default names

 (from L1 in List1 join L2 in List2 on L1.itemID equals L2.itemID select new{L1.SomePropery,L1.SomeOtherProperty).ToArray(); 
+1
source

If you want to combine two objects, you must first match the corresponding objects that you want to combine, then go through the mapped objects and copy the properties. Do not use such a LINQ query; this is not what it is intended for.

 // 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; } 
0
source

All Articles