Reputation: 1322
I am trying to construct a LINQ query in c# for the following scenario.
"Given a particular token "to identify the count of documents in which it exists"
private List<Document> documents = new List<Document>();
class Document
{
string filename;
public string FileName { get { return filename; } }
Dictionary<string, int> tokens;
public Dictionary<string, int> Tokens { get { return tokens; } }
public Document(string filename, Dictionary<string, int> tokens)
{
this.filename = filename;
this.tokens = tokens;
}
}
With my knowledge I came up with this expression:
documents.Where(d => d.Tokens.Keys.Any(k => k == word)).Count();
But I am not sure whether it is 100% correct. In need of some expert advice on this.
Upvotes: 1
Views: 72
Reputation: 46909
To make use of the O(1) lookup time of the dictionary you should use ContainsKey
instead.
documents.Count(d => d.Tokens.ContainsKey(word));
Upvotes: 3
Reputation: 5769
You can actually perform the filtering in the Count
method:
documents.Count(d => d.Tokens.Keys.Any(k => k == word));
Beyond that, I think your query is correct.
Upvotes: 1