[英]Linq Sub-select Query
我有這樣的集合
public class Worksheet
{
public string WorksheetName { get; set; }
public string WorksheetId { get; set; }
public string TestSymbol { get; set; }
public string TestId { get; set; }
public List<Samples> Samples { get; set; }
public Worksheet()
{
Samples = new List<Samples>();
}
public Worksheet(string worksheetname, string worksheetid, string testsymbol, string testid)
{
WorksheetName = worksheetname;
WorksheetId = worksheetid;
TestSymbol = testsymbol;
TestId = testid;
Samples = new List<Samples>();
}
}
public class Samples
{
public string SampleId { get; set; }
public string SampleName { get; set; }
public Samples()
{
AssociatedSheets = new List<Worksheet>();
}
public Samples(string sampleid, string samplename)
{
AssociatedSheets = new List<Worksheet>();
SampleId = sampleid;
SampleName = samplename;
}
public List<Worksheet> AssociatedSheets { get; set; }
}
出現在手表中觀看時的結構
我想要的是在每個樣本中設置AssociatedSheets以顯示包含它的工作表。
這樣才能顯示出來
我已經開發出類似這樣的東西,但顯然它不會起作用。 在此之后,我想分別選擇每個樣本。 有人可以建議:
List<Samples> AllSamples = new List<Samples>();
//Step 4. Add possible worksheets to each sample.
foreach (Samples sample in sheets.SelectMany(x => x.Samples).ToList())
{
List<Worksheet> sampleitem = sheets.SelectMany(x => x.Samples.Select(y => y.SampleId) == sheets.SelectMany(k => k.Samples).Select(h => h.SampleId).ToList());
sample.AssociatedSheets = AssociatedSheets;
if (!AllSamples.Contains(sample))
AllSamples.Add(sample);
}
[ 編輯 ]代碼修復我以前的答案
也許這可以做到:
List<Sample> allSamples = new List<Sample>();
foreach (Sample sample in sheets.SelectMany(x => x.Samples).Distinct())
{
var sampleSheets = sheets.Where(s => s.Samples.Contains(sample)).Distinct();
sample.AssociatedSheets.AddRange(sampleSheets);
allSamples.Add(sample);
}
簡單但做的工作:
foreach (var grouping in from worksheet in worksheets
from sample in worksheet.Samples
group worksheet by sample) // Groups the worksheets by sample
grouping.Key.AssociatedSheets = grouping.Distinct().ToList(); // grouping.Key is the key of the group (the sample) and ((IEnumerable)grouping) is the elements in the group (the worksheets
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.