7

基本上我希望选择两个字符串列并将它们全部放入一个字符串数组中。现在我必须做两次选择并结合结果。这不是什么大不了的事,我只是觉得它看起来很尴尬。关于如何使用一个 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", Flag = false },
        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());
    }
  }
4

2 回答 2

11

使用的替代解决方案SelectMany(它保留重复项):

var combined = list.Where(c => c.Flag)
                   .SelectMany(c => new[] { c.Present, c.Previous });
Assert.AreEqual(4, combined.Count());
于 2012-08-01T20:38:41.147 回答
0

列表中字符串的最终排序是否重要?如果没有,这似乎是完成此任务的最清晰方法:

var strings = new List<String>();
foreach (var value in list.Where(c => c.Flag))
{
    strings.Add(value.Present);
    strings.Add(value.Previous);
}
于 2012-08-01T20:36:38.097 回答