C# 使用LINQ或任何其他方式将foreach转换为优化代码
这是给定的代码行。如何以更优化的方式编写?下面的代码运行良好,但我需要另一种编写方法C# 使用LINQ或任何其他方式将foreach转换为优化代码,c#,linq,C#,Linq,这是给定的代码行。如何以更优化的方式编写?下面的代码运行良好,但我需要另一种编写方法 var attachments = new List<Attachments>(); foreach (var attachment in msg.attachments) //msg.attachments is a Dictionary<string, FileAttachment> type { var attach = new Attachments(); attach.
var attachments = new List<Attachments>();
foreach (var attachment in msg.attachments) //msg.attachments is a Dictionary<string, FileAttachment> type
{
var attach = new Attachments();
attach.name = attachment.Value.name;
attach.type = attachment.Value.type;
attachments.Add(attach);
}
var attachments=新列表();
foreach(msg.attachments中的var attachment)//msg.attachments是字典类型
{
var attach=新附件();
attach.name=attachment.Value.name;
attach.type=attachment.Value.type;
附件。添加(附加);
}
这就是你想要的吗
var attachments =
msg
.attachments
.Select(attachment => new Attachments()
{
name = attachment.Value.name,
type = attachment.Value.type,
})
.ToList();
这应该可以做到:
var attachments = msg.attachments
.Select(a => new Attachments
{
name = a.Value.name,
type = a.Value.type
})
.ToList();
但正如其他人在评论中指出的那样,这并不是真的更加优化(尽管在我看来更具可读性)
这是给定的代码行。如何以更优化的方式编写
您提到LINQ,但LINQ通常与“优化”相反——它是在牺牲效率以获得方便和(有时)简洁。您现有的代码绝对没有问题。唯一重要的调整是使用已知长度初始化目标列表:
var attachments=新列表(msg.attachments.Count);
您也可以在新附件
上使用对象初始值设定项语法,或者避免使用多个值
,但老实说,这两种方法都不可能产生任何可测量的差异。但是:
foreach(msg.attachments.Values中的var附件)
{
附件。添加(新附件){
name=attachment.name,type=attachment.type
});
}
除了使用LINQ lambda语法外,还可以使用:
它从源集合中的每个项中选择一个新的对象实例,并获取结果查询的列表
但是对于这样一段简单的代码,应该没有太大区别,只有很少的收益或损失(可以进行基准测试)
因此,这只是一个选择干净和可维护代码的问题。不要忘记:
如果您像这样使用它,您将能够利用。
如果您真的需要将它折叠成一个列表,您可以在上面调用
.ToList()
。为什么您认为LINQ是“优化的”?以什么方式进行优化?正如Llama所说,代码审查可能是满足您的请求的更好的地方。他们还会告诉你,你的类附件
应该是单数(附件
),并且有一个取名字和类型的构造函数。“我认为使用Linq,给定的代码行会更优化,工作速度更快”对不起,没有。(一般来说,这取决于具体情况。如果有疑问,请测量。)a) LINQ不太可能更快。b) 我想提出两个建议。首先,迭代msg.attachments.Values(或者如果不想这样做,请存储Value
属性的结果,而不是访问它两次)。其次,通过构造函数设置列表的容量。在发布之前,请确保阅读,因为有些事情在那里做得不同-例如,问题标题应该简单地说明代码的作用,因为问题总是“我如何改进它?”。确保代码正常工作;如果可能,包括单元测试。您可能会得到一些建议,使其更高效、更易于阅读,并更好地测试。或者msg.attachments.Values.Select(…
@JeremyLakeman当然,这也行,但是如果需要,这样你仍然可以访问密钥。我认为这两种方式都没有太大区别,除了不需要每次都执行.Value。
var attachments = ( from attachment in msg.attachments
select new Attachments
{
name = attachment.Value.name,
type = attachment.Value.type
}
).ToList();
var attachments = from att in msg.attachments
select new Attachments { name = att.Value.name, type = att.Value.type };