How to convert query syntax to method syntax

I am fooling around trying to find out what is going on in LINQ. I want to convert the following query (which works correctly) from the query syntax to the method syntax, but I cannot figure out what is right. Can someone show me the correct way to do this?

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) }; 
+6
c # linq linq-to-xml
source share
1 answer

This is actually pretty simple:

 from entry in A where B 

translates (literally) to:

 A.Where(entry=>B) 

and

 select C 

translates directly to (with "input" as our context):

 .Select(entry=>C) 

(unless it would be entry=>entry , which the compiler does not allow for non-trivial cases)

so just insert them and you are 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) }); 
+14
source share

All Articles