0

我有一组测试对象:

IList<Test> TestFromDatabase ;

public class Test 
{
    public int TestId { get; set; }
    public bool? C { get; set; }
    public bool? R { get; set; }
    public string Text { get; set; }
}

我需要把它变成一个 TestResult 对象的集合:

public class TestResult
{
    public int TestId { get; set; }
    public bool? Correct { get; set; }
}

有人可以告诉我如何使用 LINQ 做到这一点

4

2 回答 2

11

tests你的测试清单在哪里

List<Test> tests = PerformTests();
var testresults = tests.Select(x=>new TestResult { TestId = x.TestId, Correct = x.C });

我认为这C意味着正确,如果不是,您可以放其他东西。阅读更多关于从 linq 中选择的信息

IEnumerable<TestResult>如果你想让它成为一个List<TestResult>使用ToList()的话,它会产生

于 2013-09-19T12:44:40.737 回答
1

你可以按照 wudzik 的建议去做。但是,如果您的课程有很多属性,我会使用Automapper。您需要先配置自动映射器(添加映射),这里有一个指南。我总是把它放在一个引导程序类中,并在 global.asax 中调用它。对于您的示例,它将如下所示:

Mapper.CreateMap<Test, TestResult>();

配置完成后,您可以使用以下代码创建列表:

List<Test> tests = PerformTests();
List<TestResult>testresults = tests.Select(t=>Mapper.Map<Test, TestResult>(t)).ToList();

如果两个类的属性名称相同,Automapper 将知道哪个值属于哪里。否则,您将不得不稍微更改配置。对于您的示例,这将是:

Mapper.CreateMap<Test, TestResult>()
   .ForMember(dest => dest.Correct, opt => opt.MapFrom(origin => origin.C));

当您有很多属性要在 2 个类之间映射时,这种方式非常有用。

希望这会帮助你。

于 2013-09-19T13:03:23.987 回答