c# - Is it possible to replace this foreach loop with Linq? -


I have a foreach loop that I want to replace with a link query, but I do not understand how to write queries Please see my example below and TIA.

  Using the system. Colllections.Generic; Using System.Linq; Namespace Console Application {Class Example Program {Static Zero Main (string [] Args) {device device = new device (); // goal is to populate this list. Var list1 = new list & amp; Lt; IMemory & gt; (); // I would like to replace this loop with a Linq query foreach (MemoryBank MemoryBank these devices. MemoryBank) {list1.Add (memoryBank); // Memory Bank Foreign Currency (MemoryBank Memory Memory in MemoryBank) Add 1. Add (memory block); // add memory block} // var list2 = Memory by default these devices. MemoryBanks // MemoryBallsBank Select Memory Blocks // ;; }} Interface Imperial {} Public Class Device {Public ILIT & lt; Memory Bank & gt; MemoryBanks {Receive; Set; }} Public Square MemoryBank: MemoryBlock, Emmery {Public ILIT & lt; Memory block & gt; Memory Blocks {Receive; Set; }} Public class MemoryBlock: IMemory {}}    

You can:

  var list1 = device.MemoryBanks. SelektMani (M => New [] {m} .konkat (M. MemoryBlocks). Ollist ();   

Note that this is a list as your sample & lt; IMemory & gt; list instead of & lt; MemoryBlock & gt; will create the list of interface types, the last call ToList & lt; IMemory & gt; () .

Edit:

In .NET 3.5, where IEnumerable & lt; T & gt; The interface is not covalent, you can do this:

  var list1 = device.MemoryBanks. SelectionMany (m = & gt; new IMemory [] {m} .concat (M. memory block. Cast & lt; iammore & gt; ()). Olist ();    

Comments