LINQ基本操作

發表于:2008-05-07來源:作者:點擊數: 標簽:LinqLINQ
首先我們創建2個類,一個Category,一個Product public class Product{ public string Name { get ; set ; } public int CategoryID { get ; set ; }} public class Category{ public string Name { get ; set ; } public int ID { get ; set ; }} 然后創建2
首先我們創建2個類,一個Category,一個Product
public class Product { public string Name { get; set; } public int CategoryID { get; set; } } public class Category { public string Name { get; set; } public int ID { get; set; } }
  然后創建2個List的數據源
static List<Category> categories = new List<Category>() { new Category(){Name="Beverages", ID=001}, new Category(){Name="Condiments", ID=002}, new Category(){Name="Vegetables", ID=003}, new Category(){Name="Grains", ID=004}, new Category(){Name="Fruit", ID=005}, new Category(){Name="Other", ID=006} }; static List<Product> products = new List<Product>() { new Product{Name="Cola", CategoryID=001}, new Product{Name="Tea", CategoryID=001}, new Product{Name="Mustard", CategoryID=002}, new Product{Name="Pickles", CategoryID=002}, new Product{Name="Carrots", CategoryID=003}, new Product{Name="Bok Choy", CategoryID=003}, new Product{Name="Peaches", CategoryID=005}, new Product{Name="Melons", CategoryID=007}, };
  好了,現在我們開始使用LINQ了,下面使用的表達式和方法的結果是一樣的,這里的方法指Lambda表達式


  l 使用排序

  1. 使用排序時使用的顯示語句
foreach (var c in orderByResult) Console.WriteLine("ID={0},Name={1}", c.ID, c.Name);
  2. 升序 

  表達式
var orderByResult = from c in categories orderby c.ID //默認為升序,也可以在后面加上ascending select c; // 方法 var orderByResult = categories.OrderBy(c=>c.ID);
  3. 降序

  表達式
var orderByResult = from c in categories orderby c.ID descending select c; // 方法 var orderByResult = categories.OrderByDescending(c=>c.ID);

  4. 多個屬性的升序

  表達式

var orderByResult = from c in categories orderby c.ID,c.Name select c; //方法 var orderByResult = categories.OrderBy(c=>c.ID).ThenBy(c=>c.Name);
  5. 多個屬性的降序排列

  表達式
var orderByResult = from c in categories orderby c.ID, c.Name descending select c; //方法 var orderByResult = categories.OrderByDescending(c=>c.ID).ThenByDescending(c=>c.Name);

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97