2013年5月3日 星期五

Simple LINQ Examples

Example 1:

//Method 1
account.Where(m => m.Name.Contains("Cash"))
        .Where(m => m.No == "A123");

//Method 2
var query = account.Where(m => m.Name.Contains("Cash"));
query = query.Where(m => m.No == "A123");

Example 2: SQL In() and Any()

// Generate SQL IN()
int[] ids = new[] { 1, 3, 5, 7 };
account.Where(m => ids.Contains(m.Id));

// Generate SQL ANY()
int[] orders = new[] { 1, 3, 5, 7 };
account.Where(m => m.Orders.Any(i => orders.Contains(i.Id)));

Example 3: Count

account.Count(m => m.Id >= 100);
account.Where(m => m.Id >= 100).Count();

 

Example 4: Any

account.Any(m => m.Id >= 100);
account.Where(m => m.Id >= 100).Any();

Example 5: First

// Exception, if no record found
account.First(m => m.Name.Contains("Cash"));
// Null, if no record found
account.Where(m => m.Name.Contains("Cash")).FirstOrDefault();

Example 6: Single

// Exception, if record is not 1 (no record or more than 2)
account.Single(m => m.Name.Contains("Cash"));
// Exception, if record is more than 1
// Null, if no record found
account.Where(m => m.Name.Contains("Cash")).SingleOrDefault();

沒有留言:

張貼留言