gpt4 book ai didi

c# - 如何将查询语法转换为方法语法

转载 作者:太空狗 更新时间:2023-10-29 21:00:29 25 4
gpt4 key购买 nike

我正在四处游荡,试图了解 LINQ 的来龙去脉。我想将以下查询(工作正常)从查询语法转换为方法语法,但我似乎无法正确处理。谁能告诉我实现该目标的正确方法?

var logQuery = from entry in xDoc.Descendants("logentry")
where (entry.Element("author").Value.ToLower().Contains(matchText) ||
entry.Element("msg").Value.ToLower().Contains(matchText) ||
entry.Element("paths").Value.ToLower().Contains(matchText) ||
entry.Element("revision").Value.ToLower().Contains(matchText))
select new
{
Revision = entry.Attribute("revision").Value,
Author = entry.Element("author").Value,
CR = LogFormatter.FormatCR(entry.Element("msg").Value),
Date = LogFormatter.FormatDate(entry.Element("date").Value),
Message = LogFormatter.FormatComment(entry.Element("msg").Value),
ET = LogFormatter.FormatET(entry.Element("msg").Value),
MergeFrom = LogFormatter.FormatMergeFrom(entry.Element("msg").Value),
MergeTo = LogFormatter.FormatMergeTo(entry.Element("msg").Value)
};

最佳答案

其实很简单;

from entry in A
where B

翻译(字面意思)为:

A.Where(entry=>B)

和:

select C

直接翻译为(以“entry”为上下文):

.Select(entry=>C)

(除非它是 entry=>entry,编译器会在非平凡情况下忽略它)

所以只需注入(inject)这些就可以了:

var logQuery = xDoc.Descendants("logentry")
.Where(entry=>
entry.Element("author").Value.ToLower().Contains(matchText) ||
entry.Element("msg").Value.ToLower().Contains(matchText) ||
entry.Element("paths").Value.ToLower().Contains(matchText) ||
entry.Element("revision").Value.ToLower().Contains(matchText))
.Select(entry=>new
{
Revision = entry.Attribute("revision").Value,
Author = entry.Element("author").Value,
CR = LogFormatter.FormatCR(entry.Element("msg").Value),
Date = LogFormatter.FormatDate(entry.Element("date").Value),
Message = LogFormatter.FormatComment(entry.Element("msg").Value),
ET = LogFormatter.FormatET(entry.Element("msg").Value),
MergeFrom = LogFormatter.FormatMergeFrom(entry.Element("msg").Value),
MergeTo = LogFormatter.FormatMergeTo(entry.Element("msg").Value)
});

关于c# - 如何将查询语法转换为方法语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com