Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

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"));

2008/07/11

Wrapping statements

Many people (me also) like to wrap many statements into a single statement so that it looks short and clean. However, it's not a good idea in the following LINQ to SQL query:
string[] names = { "Jim", "John", "Kenny", "Mary", "Jay" };

IEnumerable<string> query = 
from n in names
where n.Length == names.Max(n1 => n1.Length)
select n;  //the output is Kenny
This query is not so efficiency because the subquery is recalculated on each outer loop and will create one more round trip to the database each time. We can improve it by separating the subquery like this:
int max = names.Max (n => n.Length);

IEnumerable<string> query = 
from n in names
where n.Length == max
select n;


PS: If you want to understand more, please refer to the C# 3.0 in a nutshell.