我正在努力学习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)
};
答案 0 :(得分:14)
实际上非常简单;
from entry in A
where B
将(字面意思)翻译为:
A.Where(entry=>B)
和
select C
直接转换为(以“entry”作为我们的上下文):
.Select(entry=>C)
(除了它是entry=>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,
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)
});