2011-05-30 59 views
26

我已經實體,稱爲客戶,它有三個屬性:內加入LINQ到實體

public class Customer { 
    public virtual Guid CompanyId; 
    public virtual long Id; 
    public virtual string Name; 
} 

我還實體,稱爲分裂,它有三個屬性:

public class Splitting { 
    public virtual long CustomerId; 
    public virtual long Id; 
    public virtual string Name; 
} 

現在我需要編寫一個獲取companyId和customerId的方法。該方法應返回與companyId中特定customerId相關的拆分清單。 事情是這樣的:

public IList<Splitting> get(Guid companyId, long customrId) {  
    var res=from s in Splitting 
      from c in Customer 
      ...... how to continue? 

    return res.ToList(); 
} 
+0

在地方分割您粘貼Customer實體的兩倍。請修復 – Ankur 2011-05-30 12:20:01

+0

@Ankur:用鼠標右鍵 - 謝謝! – Naor 2011-05-30 12:21:38

+0

爲什麼你需要公司ID在方法get ...分裂有客戶ID可用於根據傳遞的客戶ID進行選擇 – Ankur 2011-05-30 12:28:52

回答

69
var res = from s in Splitting 
      join c in Customer on s.CustomerId equals c.Id 
     where c.Id == customrId 
      && c.CompanyId == companyId 
     select s; 

使用Extension methods

var res = Splitting.Join(Customer, 
       s => s.CustomerId, 
       c => c.Id, 
       (s, c) => new { s, c }) 
      .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId) 
      .Select(sc => sc.s); 
+1

有沒有辦法將其寫入lambda查詢? – Naor 2011-05-30 12:35:56

+2

如果你的意思是linq擴展方法('Select','Join' ...看我的編輯) – manji 2011-05-30 12:47:28

2

沒有100%地肯定這兩個實體,但這裏的關係有云:

IList<Splitting> res = (from s in [data source] 
         where s.Customer.CompanyID == [companyID] && 
           s.CustomerID == [customerID] 
         select s).ToList(); 

IList<Splitting> res = [data source].Splittings.Where(
          x => x.Customer.CompanyID == [companyID] && 
           x.CustomerID == [customerID]).ToList(); 
5

你可以找到視覺工作室中的一大堆Linq例子。 只需選擇Help -> Samples,然後解壓Linq示例。

打開LINQ樣品溶液,然後打開LinqSamples.cs的SampleQueries項目

你正在尋找的答案是方法Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

var pairs = 
    from a in numbersA 
    from b in numbersB 
    where a < b 
    select new {a, b}; 
+1

我從來不知道直接在VS中獲取樣本。 +1 – ShooShoSha 2016-12-21 21:21:35

1
public IList<Splitting> get(Guid companyId, long customrId) {  
    var res=from c in Customers_data_source 
      where c.CustomerId = customrId && c.CompanyID == companyId 
      from s in Splittings_data_srouce 
      where s.CustomerID = c.CustomerID 
      select s; 

    return res.ToList(); 
}