通过使用linq将对象列表转换为字符串和整数数组来创建对象

问题描述

我试图从数据库中选择列,然后为每个列创建一个数组属性,并创建一个对象。

public class Activity
{
    public string[] Quiz { get; set; }
    public int[] CompletedCount { get; set; }
}

结果数据库输出将返回为:

IQueryable<QuizCompletedCount> results = _logContext.QuizCompletedCounts;

我从数据库中获得了以下格式的值。

Week        | Completed
---------------------------
Week 1      |   107
Week 2      |   104
Week 3      |   87
Week 4      |   49
Week 5      |   6

我以这种方式尝试过:

List<int> activityCount = new List<int>();
List<string> activity = new List<string>();

foreach (var element in results)
{
    activity.Add(element.Week);
    activityCount.Add(element.Completed);
}

var obj = new QuizActivity();
obj.CompletedCount = activityCount.ToArray();
obj.Week = activity.ToArray();

所需的输出将如下所示:

string str = "{\"Week\":[\"Week 1\",\"Week 2\",\"Week 3\",\"Week 4\",\"Week 5\"],\"CompletedCount\":[107,104,87,49,6]}";

是否有linq方法可以执行此任务而无需使用foreach以及从列表到数组的多次转换?

解决方法

您可以进行以下操作:

var result = new QuizActivity()
{
    Week = results.Select(x => x.Week).ToList(),CompletedCount = results.Select(x => x.Completed).ToList()
};