我正在努力学习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
直接翻译(以“条目”作为我们的上下文):
.Select(entry=>C)
(当它是entry =>条目时,编译器忽略了非重要的情况除外)
所以只需注入那些就完成了:
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,MergeTo = LogFormatter.FormatMergeTo(entry.Element("msg").Value) });