使用LINQ简化foreach循环(每次迭代选择两个对象) [英] Simplifying a foreach loop with LINQ (selecting two objects in each iteration)

查看:98
本文介绍了使用LINQ简化foreach循环(每次迭代选择两个对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下界面和两个类:

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 following logic that uses them:

var numbers = new[] { 1, 5, 11, 17 };

var list = new List<IMyObj>();

foreach (var n in numbers)
{
    // I'd like to simplify this part with LINQ...
    list.Add(new MyObj1(n));
    list.Add(new MyObj2(n));
}

Assert.AreEqual(8, list.Count);

测试通过了,我在list里面看到了我想要的东西-每个数字有两个对象实例:

The test passes, and I see inside list exactly what I want - two object instances per a 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}

我的问题是,如何使用LINQ简化foreach循环逻辑?我在想与 SelectMany 运算符,但我无法产生相同的输出.

My question is, how do I simplify the foreach loop logic with LINQ? I'm thinking there might be an elegant way in doing the same with the SelectMany operator perhaps, but I've not been able to produce the same output.

推荐答案

SelectMany确实是您想要的:

var list = numbers.SelectMany(n => new IMyObj[] { new MyObj1(n), new MyObj2(n) })
                  .ToList();

换句话说,对于每个数字,创建一个由两个元素组成的数组,然后使用SelectMany对其进行展平.

In other words, for each number, create a two-element array, which is then flattened using to SelectMany.

new IMyObj[]部分是必需的,而不仅仅是new[]部分,因为类型推断不能告诉您所需的数组类型.如果类型相同,则可以执行以下操作:

The new IMyObj[] part is required rather than just new[] because type inference can't tell what array type you'd want. If the types were the same, you could do something like:

var list = numbers.SelectMany(n => new[] { new MyObj(n), new MyObj(n) })
                  .ToList();

这篇关于使用LINQ简化foreach循环(每次迭代选择两个对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆