我在將一些串列合并在一起時遇到了問題,我認為這將是一個簡單的 LINQ 連接,但我認為有點復雜,而且我正在繞圈子。我有以下 3 個表:
表 1:產品總清單
| 產品 |
|---|
| 生產線1 |
| 生產線2 |
| 生產線3 |
| 產品4 |
表 2:產品和相應的傳單
| 產品 | 傳單 |
|---|---|
| 生產線1 | Docu23 |
| 生產線2 | 檔案18 |
| 生產線3 | 檔案322 |
| 產品4 | 檔案121 |
表 3:產品和相應標簽
| 產品 | 標簽 |
|---|---|
| 生產線1 | Lbl29 |
| 生產線2 | 二級 |
| 生產線3 | LBL222 |
| 生產線5 | Lbl01 |
最終結果應該是:-
| 產品 | 傳單 | 標簽 |
|---|---|---|
| 生產線1 | Docu23 | Lbl29 |
| 生產線2 | 檔案18 | 二級 |
| 生產線3 | 檔案322 | LBL222 |
| 產品4 | 檔案121 | |
| 生產線5 | Lbl01 |
注意:有些產品可以沒有傳單,有些產品可以沒有標簽。此外,傳單和標簽可以與多個產品相關聯。
這是我嘗試過的查詢,它將所有內容整合在一起,但有許多奇怪的重復行。
PMatrix = (from a in AllProducts
join b in Leaflets on a.Product equals b.Product into b_grp
from b in b_grp.DefaultIfEmpty()
join c in Labels on a.Product equals c.Product into c_grp
from c in c_grp.DefaultIfEmpty()
select new ProductMatrixModel
{
Product = a.Product,
Leaflet = b == null ? "" : b.Leaflet,
Label = c == null ? "" : c.Label
}).ToBindableCollection();
對不起,丑陋的拉伸表格,我看不到如何設定寬度。
uj5u.com熱心網友回復:
我無法測驗下面的代碼,但如果你喜歡 LINQ 運算式,你可以嘗試這樣的事情。不久前我做了類似的事情。
AllProducts
.GroupJoin(Leaflets , l => l.Product, r => r.Product, (a, b) => new ProductMatrixModel { Product = a, Leaflet = b.FirstOrDefault() ?? string.Empty })
.GroupJoin(Labels, l => l.Product, r => r.Product, (a, b) => new ProductMatrixModel { Product = a.Product , Leaflet = a.Leaflet, Label = b.FirstOrDefault() ?? string.Empty })
.ToBindableCollection();
上面的運算式使用“FirstOrDefault”,因此它將從可能的連接匹配中獲取第一個結果。如果您需要所有連接匹配,那么您需要將您的模態屬性更新為串列并相應地處理資料。
我上面提到的例子是:
將 Modal 更改為這樣的
public class ProductMatrixModel { public ProductMatrixModel() { this.Labels = new List<string>(); this.Leaflets = new List<string>(); } public string Product { get; set; } public List<string> Labels { get; set; } public List<string> Leaflets { get; set; } }然后像這樣使用 LINQ 運算式:
AllProducts .GroupJoin(Leaflets , l => l.Product, r => r.Product, (a, b) => new ProductMatrixModel { Product = a, Leaflets = b }) .GroupJoin(Labels, l => l.Product, r => r.Product, (a, b) => new ProductMatrixModel { Product = a.Product , Leaflets = a.Leaflets, Labels = b }) .ToBindableCollection();
上面的 LINQ 查詢應該會為您提供一個 IEnumerable,其中每個 ProductMatrixModel 物件都包含產品字串及其相關的標簽和傳單串列。
您可以回圈每個“ProductMatrixModel”物件,并對其關聯的資料執行任何您喜歡的操作。我假設您想以逗號分隔的字串顯示它。
以下是如何將字串串列顯示為逗號分隔字串的示例。
string.Join(",", Leaflets.Select(s => s));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341765.html
上一篇:將一個類的多個屬性聚合成一個字串
