Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string in list using linq

Tags:

c#

linq

I had a list List<string> Rank

items in list Rank are

"FF"
"ABC"
"CC"
"FF"
"FF"

I want a linq query that return value if exist and its count, suppose If i search for "FF" then it should return

value: ff
count: 3

currently i am using this query to find the match

var match = Rank.FirstOrDefault(s => s.Contains("FF"));

and this query to group the same values and assign them count.

var f = Rank.GroupBy(x => x).Select(g => new { Value = g.Key, Count = g.Count() });

i tried this but it return me complete list, it look like where clause not

var f = Rank.GroupBy(x => x).Select(g => new { Value = g.Key, Count = g.Count() }).Where(s => Rank.Contains("FF"));

can anybody know why third query is not working?

like image 805
Vijay Rana Avatar asked Dec 26 '22 17:12

Vijay Rana


1 Answers

This is nearly correct

var f = Rank.GroupBy(x => x)
            .Select(g => new { Value = g.Key, Count = g.Count() })
            .Where(s => Rank.Contains("FF"));

just change the end to so that you query newly created anonymous objects

var f = Rank.GroupBy(x => x)
            .Select(g => new { Value = g.Key, Count = g.Count() })
            .Where(s => s.Value == "FF");
like image 181
Ondrej Janacek Avatar answered Jan 07 '23 02:01

Ondrej Janacek