日期:2014-05-20 浏览次数:20926 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; namespace AnonymouseType { class AnonymouseSolve { //取得ProductID,ProductName,CategoryName public IEnumerable GetAnonymousResult() { NorthwindDataContext db = new NorthwindDataContext(); var result = db.Products.Select(p => new { 产品ID = p.ProductID, 产品名称 = p.ProductName, 类别名称 = p.Category.CategoryName }); return result; } //取得ProductID,ProductName,CategoryName的前10条记录 public IEnumerable GetTop10Result(IEnumerable _result) { var result = _result.Cast<object>(); var set = result.Select(p => new { //利用反射取得传入的匿名类型的信息 产品ID = p.GetType().GetProperty("产品ID").GetValue(p, null).ToString(), 产品名称 = p.GetType().GetProperty("产品名称").GetValue(p, null).ToString(), 类别名称 = p.GetType().GetProperty("类别名称").GetValue(p, null).ToString() }).Take(10); return set; } public IEnumerable GetTop10Result(object IEnumerableOject) { var result = (IEnumerable)IEnumerableOject; return this.GetTop10Result(result); } } }
namespace AnonymouseType { class Linker { public int ProductID { get; set; } public string ProductName { set; get; } public string CategoryName { get; set; } } }
public IEnumerable<Linker> GetAnonymousResult() { NorthwindDataContext db = new NorthwindDataContext(); var result = db.Products.Select(p => new Linker { ProductID=p.ProductID, ProductName=p.ProductName, CategoryName=p.CategoryName }) return result; } //这里的var实际上是IEnumerable<Linker> //该方法的返回值完全适用于任何需要使用linq的场合
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; namespace AnonymouseType { class Program { static void Main(string[] args) { AnonymouseSolve solve = new AnonymouseSolve(); foreach (var item in solve.GetTop10Result(solve.GetAnonymousResult())) { Console.WriteLine("-----------------------------------------"); Type itemType = item.GetType(); Console.WriteLine("产品ID:" + itemType.GetProperty("产品ID").GetValue(item, null)); Console.WriteLine("产品名称:" + itemType.GetProperty("产品名称").GetValue(item, null)); Console.WriteLine("类别名称:" + itemType.GetProperty("类别名称").GetValue(item, null)); Console.WriteLine("-----------------------------------------"); Console.WriteLine(); } var obj = (object)solve.GetAnonymousResult(); foreach (var item in solve.GetTop10Result(obj)) { Console.WriteLine("-----------------------------------------"); Type itemType = item.GetType(); Console.WriteLine("产品ID:" + itemType.GetProperty("产品ID").GetValue(item, null)); Console.WriteLine("产品名称:" + itemType.GetProperty("产品名称").GetValue(item, null)); Console.WriteLine("类别名称:" + itemType.GetProperty("类别名称").GetValue(item, null)); Console.WriteLine("-----------------------------------------"); Console.WriteLine(); } } } }