光脚丫学LINQ(009):选择各个源元素的子集
视频演示:http://u.115.com/file/f2d7193f3a
选择源序列中的各个元素的子集有两种主要方法:
1、若要只选择源元素的一个成员,请使用点运算。在下面的示例中,假定 Customer 对象包含几个公共属性,其中包括名为 City 的字符串。在执行此查询时,此查询将生成字符串输出序列。
NorthwindDataContext db = new NorthwindDataContext(); var Cities = from Customer in db.Customers select Customer.City; NorthwindDataContext db = new NorthwindDataContext(); var Cities = from Customer in db.Customers select Customer.City;
2、若要创建包含源元素的多个属性的元素,可以使用具有命名对象或匿名类型的对象初始值设定项。
下面的示例演示如何使用匿名类型来封装各个 Customer 元素的三个属性:
NorthwindDataContext db = new NorthwindDataContext(); var AllCustomers = from Customer in db.Customers select new { Customer.CustomerID, Customer.ContactName, Customer.ContactTitle }; NorthwindDataContext db = new NorthwindDataContext(); var AllCustomers = from Customer in db.Customers select new { Customer.CustomerID, Customer.ContactName, Customer.ContactTitle };
下面的演示如何使用命名类型来获取客户的编号、联系名和联系头衔:
// ************************************************* // 选择各个源元素的子集:使用命名类型对象返回多个属性。 // ************************************************* NorthwindDataContext db = new NorthwindDataContext(); var AllCustomers = from Customer in db.Customers select new CustomerObject { CustomerID = Customer.CustomerID, ContactName = Customer.ContactName, ContactTitle = Customer.ContactTitle, }; foreach (var Customer in AllCustomers) { Console.WriteLine("---------------------"); Console.WriteLine("Customer ID : {0}", Customer.CustomerID); Console.WriteLine("Customer Name : {0}", Customer.ContactName); Console.WriteLine("Contact Title : {0}", Customer.ContactTitle); }