如何使用 linq 从集合中获取特定集合?

how to get specific collection from a collection with linq?

我想获取根目录下的所有表单对象作为列表

    public class Root
    {
        public int recordsTotal { get; set; }
        public int recordsFiltered { get; set; }
        public List<Datum> Data { get; set; }
        public int ResultCode { get; set; }
    }

    public class Datum
    {
        public DateTime StartDate { get; set; }
        public DateTime StopDate { get; set; }
        public List<Evaluation> Evaluations { get; set; }
    }

    public class Evaluation
    {
        public string Evaluator { get; set; }
        public string EvaluatorUserId { get; set; }
        public Form Form { get; set; }
        public DateTime EvaluationDate { get; set; }
        public string EvaluationId { get; set; }
    }

我正在尝试使用 linq 获取它,但尚未成功

尽量减少你的 collection:

var forms = root.Data.Aggregate(
new List<Form>(),
(acc, datum) =>
{
    acc.AddRange(datum.Evaluations.Select(x => x.Form));
    return acc;
});

根据我的理解简答:

var forms = root.Data
    .SelectMany(datum => datum.Evaluations)
    .Select(evaluation => evaluation.Form)
    .ToList();

带测试的长答案

您没有指定 class Form,因此我用这个最小代码进行了测试:

using System.Collections.Generic;

namespace XUnitTestProject.Whosebug
{
    public class Root
    {
        public List<Datum> Data { get; set; }
    }

    public class Datum
    {
        public List<Evaluation> Evaluations { get; set; }
    }

    public class Form
    {
        public string Name { get; set; }
    }

    public class Evaluation
    {
        public Form Form { get; set; }
    }
}

还有一个测试class

using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace XUnitTestProject.Whosebug
{
    public class LinqTests
    {
        [Fact]
        public void Test()
        {
            var forms = CreateValidRoot().Data
                .SelectMany(datum => datum.Evaluations)
                .Select(evaluation => evaluation.Form)
                .ToList();

            Assert.Equal(2, forms.Count);
            Assert.Equal("~form1~", forms[0].Name);
            Assert.Equal("~form2~", forms[1].Name);
        }

        private static Root CreateValidRoot() => new()
        {
            Data = new List<Datum>
            {
                new()
                {
                    Evaluations = new List<Evaluation>
                    {
                        new() {Form = new Form{Name = "~form1~"}}
                    }
                },
                new()
                {
                    Evaluations = new List<Evaluation>
                    {
                        new() {Form = new Form{Name = "~form2~"}}
                    }
                }
            }
        };
    }
}