![](/img/trans.png)
[英]How to compare a List<long> with a comma-separated ids, using linq to entities
[英]Comma-separated list into column using linq
我有兩個表,它們之間具有一對多的關系,並且想要執行linq查詢,該查詢將從多表中獲取值,並從連接到表中每個記錄的值生成一個逗號分隔的列表。其他表。 我可以使用“ stuff”功能和“ for xml path”功能在sql中執行此查詢。 例如,假設我具有以下表結構:
1)區
列:ID,名稱
2)商店
列:ID,名稱,區號
現在假設我想生成一個查詢以返回以下列:district.id,district.name,stores(與該地區關聯的商店的逗號分隔列表)
如何通過linq實現?
我想在一個查詢中沒有任何for循環來執行此操作。
其他答案考慮到您具有導航屬性。 在這種情況下,您應該查看其他答案,因為在這種情況下,其他答案要簡單得多。
var result =
from d in Districts
// gets all the store names in this district
let st = Stores.Where(s => s.DistrictId == d.Id).Select(s => s.Name)
select new { Name = d.Name, Id = d.Id, Stores = string.Join(",", st) }
假設您具有導航屬性:
var q = from d in context.Districts
select new
{
DistrictID = d.id,
DistrictName = d.name,
Stores = String.Join(", ", d.stores.Select(s => s.name))
};
如果您使用的是Linq-to-SQL,則必須已經使用導航屬性創建了ORM類,然后可以運行以下代碼(我認為由於LINQ中的多元性,Store變成了Store_s_等):
var req = from dis in db.Disticts
select new {
ID = dis.id,
Name = dis.Name,
Stores =
String.Join(", ",
dis.Stores.Select( a => String.Format("{0}: {1}", a.Id, a.Name))
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.