Coolest C# LINQ/Lambdas trick you've ever pulled?

后端 未结 14 1401
死守一世寂寞
死守一世寂寞 2020-12-22 17:00

Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder...

What\'s the coolest (as in the most

14条回答
  •  温柔的废话
    2020-12-22 17:48

    Perhaps not the coolest, but recently I have been using them anytime I have a block of code that gets C+Pd over and over again only to have a few lines change. For instance, running simple SQL commands to retrieve data can be done like so:

    SqlDevice device = GetDevice();
    
    return device.GetMultiple(
        "GetPosts",
        (s) => {
            s.Parameters.AddWithValue("@CreatedOn", DateTime.Today);
    
            return true;
        },
        (r, p) => {
            p.Title = r.Get("Title");
    
            // Fill out post object
    
            return true;
        }
    );
    

    Which could return a list of Posts that were created today. This way I don't have to copy and paste the try-catch-finally block fifteen million times for each command, object, et cetera.

提交回复
热议问题