将对象列表转换为元组列表而不进行迭代 [英] Convert list of of objects to list of tuple without iterating

查看:172
本文介绍了将对象列表转换为元组列表而不进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ef对象列表中添加一个额外的参数来跟踪处理,但我一直在不得不显式初始化每个列表项。什么是正确的linq方式来做到这一点?除了简洁之外,在这种情况下linq语法是否有优势?

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.

推荐答案

您只想在这里使用投影( Select ),它将lambda表达式中的转换应用于

You just want to use a projection here ( Select ) which applies the transformation in your lambda expression to each element in the source collection.

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)会做同样的事情,这会使代码变得更糟。

The ToList() call is not entirely necessary, if you removed it then the method will return an IEnumerable<Tuple<app_subjects, bool>>. If you're just going to iterate the collection of tuples afterwards the ToList call should be removed as it forces execution (enumerates the IEnumberable) and then your next operation (the foreach) would do the same, making the code perform worse.

这篇关于将对象列表转换为元组列表而不进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆