常用Linq語句

                                    Linq就是能夠使開發人員能夠像操作數據庫那樣操作內存。

 var data = from p in lstCustomProfile orderby p.ModificationDate descending select new { p.CustomProfileid, p.Name };

 CustomProfile model = lstCustomProfile.Where(p => p.FunctionCode.Equals("SaveQueryRecord")).OrderByDescending(p => p.ModificationDate).FirstOrDefault();

  IList<CustomProfile> defaultCustoms = CustomProfileServiceAction.GetCustomProfiles(1)
                .Where(C => C.FunctionCode.Equals("Default") && C.Satus.Equals("Released"))
                .OrderBy(C => C.ProfileType).ToList();

3.Where限制

  var q =

  from p in db.Products

  group p by p.CategoryID into g

  where g.Count() >= 10

  select new {

  g.Key,

  ProductCount = g.Count(p => p.Discontinued)

  };

  語句描述:根據產品的―ID分組,查詢產品數量大於10的ID和產品數量。這個示例在Group By子句後使用Where子句查找所有至少有10種產品的類別。

DefaultIfEmpty 擴展方法

我們已經會用Empty生成空序列。 但問題是,如果你想返回一個序列當序列是空的時候包含一個默認的項目怎麼辦?

比如說,如果你正在分析測試成績列表,如果學生沒有得分,要返回一個 0:

var scores = new[] { 73, 77, 89, 90, 92, 77 };

foreach (var score in scores.DefaultIfEmpty())

{

    Console.WriteLine("The score is: " + score);

}

 

List<int> emptyScores = new List<int>();

foreach (var score in emptyScores.DefaultIfEmpty())
{
    Console.WriteLine("The score is: " + score);

}

現在,還有第二種形式的DefaultIfEmpty(),可讓您指定要使用的默認值,而不是依賴於 Default(T) 。 例如,如果我們希望得到平均分,但如果是空值就要返回一個100.

  var averageSoFar = scores.DefaultIfEmpty(100).Average();

Count

var scoreList = new List<int> { 73, 77, 89, 90, 92, 77 };
var numberOfBsOrBetter = scoreList.Count(s => s >= 80);


//爲什麼要用這個呢?既然我們有那個方便的重載

var numberOfBsOrBetter = scoreList.Where(s => s >= 80).Count();

 

 

 

 

參考資料:http://kb.cnblogs.com/page/42468/(李永京Linq To SQL)

http://developer.51cto.com/art/200911/165090.htm(Linq教程)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章