I'm fooling around trying to learn the ins an outs of LINQ. I want to convert the following query (which is working correctly) from query syntax to method syntax, but I can't seem to get it right. Can anyone show me the correct way to accomplish that?
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)
};
It is actually pretty simple;
from entry in A
where B
translates (literally) to:
A.Where(entry=>B)
and:
select C
translates directly to (with "entry" as our context):
.Select(entry=>C)
(except for when it would be entry=>entry
, which the compiler omits for non-trivial cases)
so just inject those and you're done:
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)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With