Reputation: 143
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?
Upvotes: 5
Views: 21967
Reputation: 12636
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");
Upvotes: 6
Reputation: 3626
var list = new List<string>
{
"FF", "ABC", "CC", "FF", "FF"
};
string search = "FF";
var result = list.GroupBy(l => l).Where(g => g.Key.Contains(search)).Select(s => new Tuple<string, int>(s.Key, s.Count())).FirstOrDefault();
Upvotes: 0
Reputation: 23117
Try this
var matchCount = Rank.Count(x=>x.Contains("FF"));
it will return count of strings containing "FF" in your list, if you wan't to know if there is any item that matches your predicate, do:
if(Rank.Any(x=>x.Contains("FF"))
{
...
}
Upvotes: 4