你曾经使用过的最酷的 C# LINQ/Lambdas 技巧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 08:18:03  来源:igfitidea点击:

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

提问by chakrit

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

看到一篇关于 C# 中隐藏功能的帖子,但没有多少人写过 linq/lambdas 示例,所以......我想知道......

What's the coolest (as in the most elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written?

您见过/编写的 C# LINQ 和/或 Lambdas/匿名委托的最酷(如最优雅的)用法是什么?

Bonus if it has went into production too!

如果它也已投入生产,则奖励!

回答by Markus Olsson

The LINQ Raytracercertainly tops my list =)

LINQ光线跟踪肯定顶我的名单=)

I'm not quite sure if qualifies as elegant but it is most certainly the coolest linq-expression I've ever seen!

我不太确定是否符合优雅,但它肯定是我见过的最酷的 linq 表达式!

Oh, and just to be extremely clear; I did notwrite it (Luke Hobandid)

哦,只是要非常清楚;不是我写的(Luke Hoban写的)

回答by Ian Patrick Hughes

I was trying to come up with a cool way to build a navigation control for a website I was building. I wanted to use regular HTML unordered list elements (employing the standard CSS "Sucker Fish" look) with a top-navigation mouse-over effect that reveals the drop down items. I had a sql dependent cached DataSet with two tables (NavigationTopLevels & NavigationBottomLevels). Then all I had to was create two class objects (TopNav & SubNav) with the few required properties (the TopNav class had to have a generic list of bottomnav items -> List<SubNav> SubItems).

我试图想出一种很酷的方法来为我正在构建的网站构建导航控件。我想使用常规的 HTML 无序列表元素(采用标准的CSS“Sucker Fish”外观)和顶部导航鼠标悬停效果,显示下拉项目。我有一个带有两个表(NavigationTopLevels 和 NavigationBottomLevels)的 sql 相关缓存数据集。然后我所要做的就是创建两个类对象(TopNav 和 SubNav),其中包含一些必需的属性(TopNav 类必须有一个底部导航项目的通用列表 -> List<SubNav> SubItems)。


var TopNavs = from n in ds.NavigationTopLevels select new TopNav { NavigateUrl = String.Format("{0}/{1}", tmpURL, n.id), Text = n.Text, id = n.id, SubItems = new List<SubNav>( from si in ds.NavigationBottomLevels where si.parentID == n.id select new SubNav { id = si.id, level = si.NavLevel, NavigateUrl = String.Format("{0}/{1}/{2}", tmpURL, n.id, si.id), parentID = si.parentID, Text = si.Text } ) }; List<TopNav> TopNavigation = TopNavs.ToList();

It might not be the "coolest" but for a lot of people who want to have dynamic navigation, its sweet not to have to muddle around in the usual looping logic that comes with that. LINQ is, if anything a time saver in this case.

它可能不是“最酷的”,但对于很多想要动态导航的人来说,不必在随之而来的通常循环逻辑中糊涂是一件好事。在这种情况下,LINQ 可以节省时间。

回答by Chris Ammerman

Some basic functionals:

一些基本功能:

public static class Functionals
{
    // One-argument Y-Combinator.
    public static Func<T, TResult> Y<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> F)
    {
        return t => F(Y(F))(t);
    }

    // Two-argument Y-Combinator.
    public static Func<T1, T2, TResult> Y<T1, T2, TResult>(Func<Func<T1, T2, TResult>, Func<T1, T2, TResult>> F)
    {
        return (t1, t2) => F(Y(F))(t1, t2);
    }

    // Three-arugument Y-Combinator.
    public static Func<T1, T2, T3, TResult> Y<T1, T2, T3, TResult>(Func<Func<T1, T2, T3, TResult>, Func<T1, T2, T3, TResult>> F)
    {
        return (t1, t2, t3) => F(Y(F))(t1, t2, t3);
    }

    // Four-arugument Y-Combinator.
    public static Func<T1, T2, T3, T4, TResult> Y<T1, T2, T3, T4, TResult>(Func<Func<T1, T2, T3, T4, TResult>, Func<T1, T2, T3, T4, TResult>> F)
    {
        return (t1, t2, t3, t4) => F(Y(F))(t1, t2, t3, t4);
    }

    // Curry first argument
    public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(Func<T1, T2, TResult> F)
    {
        return t1 => t2 => F(t1, t2);
    }

    // Curry second argument.
    public static Func<T2, Func<T1, TResult>> Curry2nd<T1, T2, TResult>(Func<T1, T2, TResult> F)
    {
        return t2 => t1 => F(t1, t2);
    }

    // Uncurry first argument.
    public static Func<T1, T2, TResult> Uncurry<T1, T2, TResult>(Func<T1, Func<T2, TResult>> F)
    {
        return (t1, t2) => F(t1)(t2);
    }

    // Uncurry second argument.
    public static Func<T1, T2, TResult> Uncurry2nd<T1, T2, TResult>(Func<T2, Func<T1, TResult>> F)
    {
        return (t1, t2) => F(t2)(t1);
    }
}

Don't do much good if you don't know how to use them. In order to know that, you need to know what they're for:

如果你不知道如何使用它们,就不要做得很好。为了知道这一点,您需要知道它们的用途:

回答by Samuel Hyman

Progress Reportingfor long running LINQ queries. In the blog post you can find an extension method WithProgressReporting() that lets you discover and report the progress of a linq query as it executes.

长时间运行的 LINQ 查询的进度报告。在博客文章中,您可以找到一个扩展方法 WithProgressReporting(),它可以让您发现并报告 linq 查询的执行进度。

回答by Aaron Powell

Not my design but I've used it a few times, a typed-switch statement: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

不是我的设计,但我已经用过几次了,一个 typed-switch 语句:http: //community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch .aspx

Saved me so many if... else if... else if... else IF! statements

救了我这么多如果……否则如果……否则如果……否则如果!声明

回答by ThatBloke

I think that LINQ is a major change to .NET and it is a very powerful tool.

I use LINQ to XML in production to parse and filter records from a 6MB XML file (with 20+ node levels) into a dataset in two lines of code.

Before LINQ this would have taken hundreds of lines of code and days to debug.

That's what I call elegant!

我认为 LINQ 是对 .NET 的重大改变,它是一个非常强大的工具。

我在生产中使用 LINQ to XML 将 6MB XML 文件(具有 20 多个节点级别)中的记录解析和过滤到两行代码中的数据集。

在 LINQ 之前,这需要数百行代码和数天才能进行调试。

这就是我所说的优雅!

回答by Aaron Powell

Actually, I'm quite proud of this for generating Excel docments: http://www.aaron-powell.com/linq-to-xml-to-excel

实际上,我为生成 Excel 文档感到非常自豪:http://www.aaron-powell.com/linq-to-xml-to-excel

回答by Bryan Watts

Working with attributes:

使用属性:

private void WriteMemberDescriptions(Type type)
{
    var descriptions =
        from member in type.GetMembers()
        let attributes = member.GetAttributes<DescriptionAttribute>(true)
        let attribute = attributes.FirstOrDefault()
        where attribute != null
        select new
        {
            Member = member.Name,
            Text = attribute.Description
        };

        foreach(var description in descriptions)
        {
            Console.WriteLine("{0}: {1}", description.Member, description.Text);
        }
}

The GetAttributesextension method:

GetAttributes扩展方法:

public static class AttributeSelection
{
    public static IEnumerable<T> GetAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute
    {
        if(provider == null)
        {
            throw new ArgumentNullException("provider");
        }

        return provider.GetCustomAttributes(typeof(T), inherit).Cast<T>();
    }
}

AttributeSelectionis production code and also defines GetAttributeand HasAttribute. I chose to use the letand whereclauses in this example.

AttributeSelection是生产代码,还定义了GetAttributeHasAttribute。我选择在这个例子中使用letandwhere子句。

回答by Tomas Petricek

I did one (a bit crazy, but interesting) thing like that just recently:

我最近做了一件(有点疯狂,但很有趣)这样的事情: