tags:

views:

62

answers:

2

I want to convert this LINQ code

var x = from nm in names 
        select MyClass.SomeMethod(nm).TrimStart(',');
foreach (var vv in x)
{
    // I want to group and count different types of vv here
}

to use shorter syntax, one where they do x => x in LINQ. I also want to group and count 'vv' (there could be number of similar vv's)

+3  A: 

Well, the "dot notation" or "fluent notation" for the above is:

var x = names.Select(nm => MyClass.SomeMethod(nm).TrimStart(','));

For grouping:

var x = names.Select(nm => MyClass.SomeMethod(nm).TrimStart(','));
             .GroupBy(vv => vv, 
                      (key, group) => new { Key = key, Count = group.Count() });
Jon Skeet
Is the dotnotation LINQ?
Martejk
@Martejk: It's LINQ either way, IMO.
Jon Skeet
A: 

Something like this?

MyClass.SomeMethod(names).TrimStart(',')
.GroupBy(x => x.vv)
.ToList()
.ForEach(x => Console.WriteLine(x.Key + ": " + x.Count()));
Lee Sy En
It's better to write you own `ForEach` extension method rather thatn converting to `List<T>`
abatishchev
@abatishchev: I'd say it's better to write a simple foreach statement than to write your own extension method...
Jon Skeet
@Jon: Could you please point me to some discussion why OEM - own ext method :) - is not very good idea?
abatishchev
@abatishchev: It seems silly to use a convoluted approach when the language has foreach built in... Eric Lippert goes into this in more detail: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
Jon Skeet