2011-06-15 74 views
1

我有一個名爲Quotes的SQL表。如何搜索LINQ SQL在LIST中的值<object>

而在C#用戶,我有:

Public class Locations 
{ 
public string cityname { get; set; } 
} 

List<Locations> = new puLocations List<Locations> // Pickup Locations 
List<Locations> = new delLocations List<Locations> // Delivery Locations 

現在我想尋找我的報價表,這些名單..這樣的事情(這顯然不工作)

var quotes = from q in db.Quotes 
where q.PULocations in puLocations //puLocatiosn is the list<Locations> 
and q.DELLocations in delLocations 
select q; 

所以我希望它返回任何比賽..即如果在PU位置我有黃金海岸,悉尼,布里斯班。和交貨地點,我有珀斯,霍巴特 它應該返回黃金海岸 - >珀斯 黃金海岸 - >霍巴特 悉尼 - >珀斯 悉尼 - >黃金海岸 ....等(如果存在這些引號)

回答

1

首先,你需要這個

List<Locations> puLocations= new List<Locations>() // Pickup Locations 
List<Locations> delLocations = new List<Locations>() // Delivery Locations 

然後你要使用像.Contains()擴展方法:

var quotes = from q in db.Quotes where q.PULocations.Contains(puLocations) and 
q.DELLocations.Contains(delLocations) select q; 
+1

'Contains'不是LINQ擴展方法;它一直在那裏'List '有。 – 2011-06-15 02:11:01

+0

你是對的,我超前了。謝謝 – esastincy 2011-06-15 02:12:54

0

爲了不MAK你e生活困難,你應該在20dB此操作,我敢打賭,你有你的數據庫有報價 所以假設你有他們喜歡db.Locations.Where(l=>l.type==DEL)db.Locations.Where(l=>l.type==PU)你會寫下面的查詢皮卡和交貨地點一起

var quotes = from q in db.Quotes 
    join del in db.Locations on del equals q.DELLocations 
    join pu in db.Locations on pu equals q.PULocations 
    where pu.type == PU && del.type == DEL && whateverelseyou need 
    select q; 

情況下也真有你的數據庫約束,他們將傳播作爲導航屬性,所以你LINQ查詢看起來像下面

var quotes = from q in db.Quotes where q.DELLocation.field == something && q.PULocation.field == something 

但它可能不會是這樣。

最後一個,你可以去的辦法就是利用實體SQL語句IN,並寫長語句像下面

// you build string specifying as many parameters as you have items in your lists 
    var entitySQL = "select quote FROM [Quotes] WHERE quote.DELLocation.LocationID IN (@delparam1, @delparam2,....) AND quote.PULocation.LocationID in (@puparam1, @puparam2,....)" 
    // then you create ObjectParameterCollection to substitute your IDs to ObjectQuery 
    var opc = new ObjectParameterCollection(); 
    opc.Add("@delparam1", DELLocation[0].LocationID) // obviously you'll do it using linq 
    opc.Add("@puparam1", PULocation[0].LocationID) 

    // create object query 

    var quotes = db.CreateQuery<Quote>(entitySQL, opc);