Linq 子选择查询



我有这样的集合

    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; }
    }

在手表中查看时显示的结构

  • 工作表 1
    • 样本 A
    • 样本 B
  • 工作表 2
    • 样本 C
    • 样本 A

我想要的是在每个示例中设置关联工作表以显示包含它的工作表。

以便它显示

  • 工作表 1
    • 样本 A
      • 工作表 1
      • 工作表 2
    • 样本 B
      • 工作表 1
  • 工作表 2
    • 样本 C
      • 工作表 2
    • 样本 A
      • 工作表 1
      • 工作表 2

我已经开发了这样的东西,但显然它不起作用。在此之后,我想区分选择每个样本。有人可以建议:

        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);
        }

简单但要完成工作:

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

[编辑] 我以前的答案中的代码修复

也许这可以做到:

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);
}

相关内容

  • 没有找到相关文章

最新更新