c# – 使用LINQ将select中两列的结果合并为一个数组?

前端之家收集整理的这篇文章主要介绍了c# – 使用LINQ将select中两列的结果合并为一个数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
基本上我想要选择两个字符串列并将它们全部放入一个字符串数组中.现在我必须做两个选择并结合结果.这不是什么大不了的事,我觉得它看起来很尴尬.有关如何使用一个 linq语句实现相同目标的任何建议?这是一个我正在使用的测试用例:
[TestFixture]
  public class test {

    public class Values {
      public string Present { get; set; }
      public string PrevIoUs { get; set; }
      public bool Flag { get; set; }
    }

    [Test]
    public void test1() {

      var list = new List<Values> {
        new Values { Present = "present1",PrevIoUs = "prevIoUs1",Flag = false },new Values { Present = "present2",PrevIoUs = "prevIoUs2",new Values { Present = "present3",PrevIoUs = "prevIoUs3",Flag = true },new Values { Present = "present4",PrevIoUs = "prevIoUs4",Flag = true }
      };


      var r1 = list.Where(c => c.Flag).Select(c => c.Present);
      var r2 = list.Where(c => c.Flag).Select(c => c.PrevIoUs);
      var combined = r1.Concat(r2);

      Assert.AreEqual(4,combined.Count());
    }
  }

解决方法

使用SelectMany的另一种解决方案(它保留重复项):
var combined = list.Where(c => c.Flag)
                   .SelectMany(c => new[] { c.Present,c.PrevIoUs });
Assert.AreEqual(4,combined.Count());
原文链接:https://www.f2er.com/csharp/243952.html

猜你在找的C#相关文章