2013/07/15

LINQ: Ways to have two filters.

string[] source = new string[5] { "12345", "1234", "45678", "6789", "6" };

// Method 1
var result1 = from o in source
where o.Length > 4 && o.StartsWith("1")
select o;
// Method 2
var result2 = from o in source
where (o.Length > 4 & o.StartsWith("1"))
select o;
// Method 3
var result3 = from o in source
where o.Length > 4
where o.StartsWith("1")
select o;
// Method 4
var result4 = source.Where(o => o.Length > 4).Where(o => o.StartsWith("1"));

Different style:
string[] source = new string[5] { "12345""1234""45678""6789""6" };

// Method 1
var result1 = from o in source
              where o.Length > 4 && o.StartsWith("1")
              select o;
// Method 2
var result2 = from o in source
              where (o.Length > 4 & o.StartsWith("1"))
              select o;
// Method 3
var result3 = from o in source
              where o.Length > 4
              where o.StartsWith("1")
              select o;
// Method 4
var result4 = source.Where(o => o.Length > 4).Where(o => o.StartsWith("1"));

No comments:

Post a Comment