Combine the results of two columns in a selection into one array with LINQ?

Basically I am looking to select both string columns and put all this into one array of strings. Now I need to make two choices and combine the results. This is not a huge deal, I just think it looks awkward. Any suggestions on how to accomplish the same goal with a single linq expression? Here is a test case that I use for clutter:

[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
source share
2 answers

An alternative solution using SelectMany (it stores duplicates):

 var combined = list.Where(c => c.Flag) .SelectMany(c => new[] { c.Present, c.Previous }); Assert.AreEqual(4, combined.Count()); 
+8
source

Does the final order of the lines in the list matter? If not, it seems like this would be the clearest way to achieve this:

 var strings = new List<String>(); foreach (var value in list.Where(c => c.Flag)) { strings.Add(value.Present); strings.Add(value.Previous); } 
0
source

All Articles