Linq子选择查询

时间:2013-01-25 09:48:02

标签: c# .net linq lambda entity-relationship

我有一个像这样的集合

    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

我想要的是在每个样本中设置AssociatedSheets以显示包含它的工作表。

这样就显示了

  • 工作表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);
        }

2 个答案:

答案 0 :(得分:1)

[编辑]代码修复我之前的回答

也许这可以做到:

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

答案 1 :(得分:1)

简单但完成工作:

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