5

I'm trying to add an extra parameter to a list of ef objects to track processing, but I keep running into having to initialize each list item explicitly. What's the correct linq way to do this? Aside from terseness, is there any advantage to a linq syntax in this case?

List<app_subjects> subjectList = AppMySQLQueries.GetAllSubjects();
List<Tuple<app_subjects, bool>> subjectCollection = new List<Tuple<app_subjects, bool>>(subjectList.Count);

foreach (app_subjects subject in subjectList)
{
     subjectCollection.Add(Tuple.Create(subject, false));
}

I have searched the site without success.

4

3 回答 3

14

您只想在此处使用投影 ( Select),它将 lambda 表达式中的转换应用于源集合中的每个元素。

List<Tuple<app_subjects, bool>> tuples = subjectList.Select(x => new Tuple<app_subjects, bool>(x, false)).ToList();

ToList()调用并非完全必要,如果您将其删除,则该方法将返回一个IEnumerable<Tuple<app_subjects, bool>>. 如果您只是要在之后迭代元组集合,则ToList应该删除调用,因为它强制执行(枚举IEnumberable),然后您的下一个操作(foreach)也会这样做,从而使代码执行得更糟。

于 2013-09-06T18:33:19.683 回答
7

像这样?

subjectList.Select(s => Tuple.Create(s, false)).ToList();
于 2013-09-06T18:25:30.117 回答
0

尝试这个。

List<Tuple<app_subjects, bool>> subjectCollection = subjectList.CovertAll( subject => new Tuple<app_subjects, bool>(){
subject,
false
}).ToList();
于 2013-09-06T18:30:21.860 回答