Quick LINQ Trick

cool way to shorten and make your code more readable with LINQ

Say I have this function:
public string DoStuff(string s) 
{ 
    //whole bunch of stuff
    return s; 
}

Now say I have the following:
public IEnumerable DoThings(IEnumerable strs) 
{  
    var ret = new list();
    foreach(var s in strs)
        ret.Add(DoStuff(s));
    return ret;
}

Which can be reduced to:
public IEnumerable DoThings(IEnumerable strs) 
{  
    foreach(var s in strs)
        yield return DoStuff(s);
}

Or...
public IEnumerable DoThings(IEnumerable strs) 
{  
    strs.Select(x => DoStuff(x));
}

but even further you can simply take it to:
public IEnumerable DoThings(IEnumerable strs) 
{  
    strs.Select(DoStuff);
}

Since the enumeration is already strings, the Select statement knows just to pass them through the method supplied. With it this small, the method is almost useless to write out:
// Tnstead of:
var x = DoThings(strs);

// you can simply substitute: 
var y = strs.Select(DoStuff);

// giving you the same results without having to write 
// a method

It's nothing revolutionary, but can clean up your code where applicable.
Comments are closed