Reputation: 72
While reading Linq to Objects from msdn I got a sample query https://msdn.microsoft.com/en-us/library/bb546163.aspx The example was in linq query form which I tried to convert to method form. The query includes a let
keyword. I need suggestion on how the method form I written can be optimized, more specifically how to handle let
when converting to method form.
So far I tried this much
internal static string[] GetSpecificSentenceContainingParticularWords(
string sentenceToSearch,
string[] WordsToMatch)
{
if (string.IsNullOrEmpty(sentenceToSearch)
|| WordsToMatch == null
|| WordsToMatch.Count() == 0)
return null;
string[] sentences = sentenceToSearch.Split(new char[] { '.' });
var returnSentences = from s in sentences
let w = s.Split(new char[] { ' ' })
where w.Distinct().Intersect(WordsToMatch).Count()
== WordsToMatch.Count()
select s;
returnSentences = sentences.Where((s) =>
{
var a = s.Split(new char[] { ' ' }); //splitting a sentence to words
return (a.Distinct().Intersect(WordsToMatch).Count() == WordsToMatch.Count());
});
return returnSentences.ToArray<string>();
}
Upvotes: 0
Views: 639
Reputation: 1643
I personally prefer method syntax for every scenario with the exception of this one. With method syntax you have to store your calculated value as a property on an anonymous object. With query syntax and let
you don't have to jump through any hoops.
I would not attempt an "optimization" by converting it to method syntax.
If however you want to optimize the code beyond just converting it to method syntax, you can cut it down to one call to Except
and one check that the result is empty.
Upvotes: 0
Reputation: 32296
Technically you don't even need the let
in the first place
var returnSentences = from s in sentences
where s.Split(new char[] { ' ' })
.Distinct()
.Intersect(WordsToMatch)
.Count() == WordsToMatch.Count()
select s;
So you could just do
var returnSentences = sentences.Where(s => s.Split(new char[] { ' ' })
.Distinct()
.Intersect(WordsToMatch)
.Count() == WordsToMatch.Count());
Upvotes: 0