是否有可能用Linq替换这个foreach循环?
我有一个foreach循环,我想用Linq查询替换,但我无法弄清楚如何编写查询。 请参阅下面的示例和TIA。
using System.Collections.Generic; using System.Linq; namespace ConsoleApplication { class ExampleProgram { static void Main( string[] args ) { Device device = new Device(); // The goal is to populate this list. var list1 = new List(); // I would like to replace this loop with a Linq query foreach( MemoryBank memoryBank in device.MemoryBanks ) { list1.Add( memoryBank ); // add the memory bank foreach( MemoryBlock memoryBlock in memoryBank.MemoryBlocks ) list1.Add( memoryBlock ); // add the memory block } //var list2 = from memoryBank in device.MemoryBanks // from memoryBlock in memoryBank.MemoryBlocks // select ???; } } interface IMemory {} public class Device { public IList MemoryBanks { get; set; } } public class MemoryBank : MemoryBlock, IMemory { public IList MemoryBlocks { get; set; } } public class MemoryBlock : IMemory { } }
你可以做:
var list1 = device.MemoryBanks .SelectMany(m => new[] { m }.Concat(m.MemoryBlocks)) .ToList();
请注意,这将创建List
而不是样本中的List
。 要创建接口类型列表,请进行最终调用ToList
。
编辑:
在.NET 3.5中, IEnumerable
接口不是协变的,你可以这样做:
var list1 = device.MemoryBanks .SelectMany(m => new IMemory[] { m } .Concat(m.MemoryBlocks.Cast())) .ToList();
像这样的东西应该工作:
list1 = device.MemoryBanks .Select( x=> x.MemoryBlocks.AsEnumerable().Concat(x)) .SelectMany( x=>x) .ToList();