Given the following interface and two classes:
public interface IMyObj { int Id { get; set; } } public class MyObj1 : IMyObj { public MyObj1(int id) { Id = id; } public int Id { get; set; } public override string ToString() => $"{GetType().Name} : {Id}"; } public class MyObj2 : IMyObj { public MyObj2(int id) { Id = id; } public int Id { get; set; } public override string ToString() => $"{GetType().Name} : {Id}"; }
And given the following logic that uses them:
var numbers = new[] { 1, 5, 11, 17 }; var list = new List<IMyObj>(); foreach (var n in numbers) {
The test passes, and I see exactly what I want inside the list - two instances of the object per number:
Count = 8 [0]: {MyObj1 : 1} [1]: {MyObj2 : 1} [2]: {MyObj1 : 5} [3]: {MyObj2 : 5} [4]: {MyObj1 : 11} [5]: {MyObj2 : 11} [6]: {MyObj1 : 17} [7]: {MyObj2 : 17}
My question is: how to simplify the logic of a foreach with LINQ? I think there may be an elegant way to do the same with SelectMany , perhaps, but I could not produce the same result.
c # linq
Pompair
source share