RBrook
RBrook

Reputation: 23

How to make difficult group with count on C# (linq)?

I have trouble with text analysts. Need to count words iteration in .txt files I made it, but I need to put all counts together without separating on files.

How to rewrite with grouping correct?

var queryMatchingFiles =
            from file in files
            where file.Extension == ".txt"
            let fileText = File.ReadAllText(file.FullName)
            let matches = Regex.Matches(fileText, searchTerm)
            select new
            {
                matchedValues = from Match match in matches
                                group match by match.Value into grp
                                select new {
                                    key = grp.Key, value = grp.Count()
                                }
            };

Upvotes: 2

Views: 72

Answers (1)

arekzyla
arekzyla

Reputation: 2898

Your query should look like this:

var queryMatchingFiles =
            from file in files
            where file.Extension == ".txt"
            let fileText = File.ReadAllText(file.FullName)
            from match in Regex.Matches(fileText, searchTerm).Cast<Match>()
            group match by match.Value into grp
            select new
            {
                key = grp.Key,
                value = grp.Count()
            };

To create IEnumerable<Match> from matches you can use:

Regex.Matches(fileText, searchTerm).Cast<Match>()

So you can write query like from match in ...

Another option to cast is by explicitly specifying the type in expression:

from Match match in Regex.Matches(fileText, searchTerm)

Upvotes: 1

Related Questions