C#3。0 LINQ 操作符

Table 类:

public class DemoDataContext : DataContext
{
  public DemoDataContext (string cxString) : base (cxString) {}

  public Table<Customer> Customers { get { return GetTable<Customer>(); } }
  public Table<Purchase> Purchases { get { return GetTable<Purchase>(); } }
}

[Table] public class Customer
{
  [Column(IsPrimaryKey=true)]  public int ID;
  [Column]                     public string Name;

  [Association (OtherKey="CustomerID")]
  public EntitySet<Purchase> Purchases = new EntitySet<Purchase>();
}

[Table] public class Purchase
{
    [Column(IsPrimaryKey=true)]  public int ID;
    [Column]                     public int CustomerID;
    [Column]                     public string Description;
    [Column]                     public decimal Price;
    [Column]                     public DateTime Date;

  EntityRef<Customer> custRef;

  [Association (Storage="custRef",ThisKey="CustomerID",IsForeignKey=true)]
  public Customer Customer
  {
    get { return custRef.Entity; } set { custRef.Entity = value; }
  }
}

使用SQL来创建表:

create table Customer
(
  ID int not null primary key,
  Name varchar(30) not null
)
create table Purchase
(
  ID int not null primary key,
  CustomerID int not null references Customer (ID),
  Description varchar(30) not null,
  Price decimal not null
)

Join和GroupJoin实现:

public static IEnumerable <TResult> Join
                                    <TOuter,TInner,TKey,TResult> (
  this IEnumerable <TOuter>     outer,
  IEnumerable <TInner>          inner,
  Func <TOuter,TKey>            outerKeySelector,
  Func <TInner,TKey>            innerKeySelector,
  Func <TOuter,TInner,TResult>  resultSelector)
{
  ILookup <TKey, TInner> lookup = inner.ToLookup (innerKeySelector);
  return
    from outerItem in outer
    from innerItem in lookup [outerKeySelector (outerItem)]
    select resultSelector (outerItem, innerItem);
}
public static IEnumerable <TResult> GroupJoin
                                    <TOuter,TInner,TKey,TResult> (
  this IEnumerable <TOuter>     outer,
  IEnumerable <TInner>          inner,
  Func <TOuter,TKey>            outerKeySelector,
  Func <TInner,TKey>            innerKeySelector,
  Func <TOuter,IEnumerable<TInner>,TResult>  resultSelector)
{
  ILookup <TKey, TInner> lookup = inner.ToLookup (innerKeySelector);
  return
    from outerItem in outer
    select resultSelector
     (outerItem, lookup [outerKeySelector (outerItem)]);
}
发布了573 篇原创文章 · 获赞 223 · 访问量 228万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览