什么时候应该将 LINQ 用于 C#?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2186724/
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-07 00:12:17  来源:igfitidea点击:

When should I use LINQ for C#?

c#.netlinq

提问by nubela

I'm learning C#, and I find LINQ absolutely interesting. However what is boggling me is, I can't think of a scenario whereby using LINQ would be an immense help, as its really not that hard replicating LINQ features in code.

我正在学习 C#,我发现 LINQ 非常有趣。然而,让我感到困惑的是,我想不出使用 LINQ 会有很大帮助的场景,因为在代码中复制 LINQ 功能真的不是那么难。

Any personal experiences/suggestions you might wanna share?

您可能想分享任何个人经验/建议?

Thanks!

谢谢!

采纳答案by tvanfosson

I find that I'm using LINQ just about any time that I would have previously written a loop to fill a container. I use LINQ to SQL as my ORM and lots of LINQ everywhere else.

我发现几乎在我之前编写循环来填充容器的任何时候都在使用 LINQ。我使用 LINQ to SQL 作为我的 ORM,并在其他地方使用了许多 LINQ。

Here's a little snippet that I wrote for an Active Directory helper class that finds out if a particular user is an a particular group. Note the use of the Any() method to iterate over the user's authorization groups until it finds one with a matching SID. Much cleaner code than the alternative.

这是我为 Active Directory 帮助程序类编写的一个小片段,用于确定特定用户是否属于特定组。请注意使用 Any() 方法迭代用户的授权组,直到找到具有匹配 SID 的授权组。比替代方案更干净的代码。

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }
    return user.GetAuthorizationGroups()
               .Any( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 );
}

Alternative:

选择:

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }
    bool inGroup = false;
    foreach (var g in user.GetAuthorizationGroups())
    {
         if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
         {
            inGroup = true;
            break;
         }
    }
    return inGroup;
}

or

或者

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }

    foreach (var g in user.GetAuthorizationGroups())
    {
         if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
         {
            return true;
         }
    }
    return false;
}

Here's a snippet that does a search against a repository, orders, and converts the first 10 matching business objects into a view-specific model (Distanceis the Levenshtein edit distance of the matching model's unique id from the uniqueID parameter).

这是一个片段,它对存储库进行搜索、订购并将前 10 个匹配的业务对象转换为特定于视图的模型(Distance是匹配模型的唯一 id 与 uniqueID 参数的编辑距离)。

model.Results = this.Repository.FindGuestByUniqueID( uniqueID, withExpired )
                               .OrderBy( g => g.Distance )
                               .Take( 10 )
                               .ToList()
                               .Select( g => new GuestGridModel( g ) );

回答by FrustratedWithFormsDesigner

I find LINQ useful when I have a collection of some object and I'm interested in items that meet a certain criteria. Simple example would be searching for all shapes in a collection of shapes that are circles.

当我有一些对象的集合并且我对满足特定条件的项目感兴趣时,我发现 LINQ 很有用。简单的例子是在一组圆形的形状中搜索所有形状。

var circles =
        from s in allShapes
        where s.Type == ShapeTypes.Circle
        select s;

I admit I could have just written a loop with some code in it, but I find this code shorter and easier to write, and easier to read and understand.

我承认我可以只写一个包含一些代码的循环,但我发现这段代码更短、更容易编写,也更容易阅读和理解。

LINQ can also be used with databases, but I actually find I don't do that very much. To each his/her own, I guess.

LINQ 也可以与数据库一起使用,但我实际上发现我很少这样做。我猜每个人都是他/她自己的。

回答by galaktor

I use LINQ to DataSet a lot for working with DataTables. DataTables are generic data storages where I often store values e.g. from a loaded CSV file. It is much more readable and comfortable to use LINQ for querying or joining data instead of "brute-force"-ing with for-loops.

我经常使用 LINQ to DataSet 来处理数据表。DataTables 是通用数据存储,我经常在其中存储值,例如来自加载的 CSV 文件。使用 LINQ 来查询或连接数据,而不是使用 for 循环进行“蛮力”操作,可读性和舒适度更高。

回答by Kenny Mann

For me, I pretty much only use it to access databases. I almost never query on XML or list's.

对我来说,我几乎只用它来访问数据库。我几乎从不查询 XML 或列表。

回答by Brian Mains

Yes, you can easily use LINQ to Objects using alternative code, and it's not tha difficult. I tend to like the semantics of the lambda expressions, and it does wrap several lines of code into one. But a lot of operations you can do with your own code, except some of the bigger operations (union, intersect, etc.) are easier to do with LINQ.

是的,您可以使用替代代码轻松地使用 LINQ to Objects,而且这并不困难。我倾向于喜欢 lambda 表达式的语义,它确实将几行代码包装成一行。但是很多操作你可以用你自己的代码来完成,除了一些更大的操作(联合、相交等)用 LINQ 更容易完成。

LINQ has other flavors; LINQ to XML makes it really nice to work with XML data. I really like it better than the previous objects available.

LINQ 有其他风格;LINQ to XML 使处理 XML 数据变得非常好。我真的比以前可用的对象更喜欢它。

LINQ to SQL and ADO.NET Entity Framework (with LINQ to Entities) are an object relational mapper and can map to your database tables, and act like stored procedures and ADO.NET datasets do, so that is a very nice alternative than weak datasets/datatables, and I like it over strongly typed datasets/tables too.

LINQ to SQL 和 ADO.NET 实体框架(带有 LINQ to Entities)是一个对象关系映射器,可以映射到您的数据库表,并像存储过程和 ADO.NET 数据集一样工作,因此这是比弱数据集更好的选择/datatables,我也喜欢它而不是强类型的数据集/表。

HTH.

哈。

回答by Greg

I find it useful to transform/"project" data before binding it to a grid for read-only purposes.

我发现在将数据绑定到网格以用于只读目的之前转换/“投影”数据很有用。

回答by Tomas Vana

The LINQ language feature set is not replicable so easily in C# 2.0 code, without extension methods, lambda expressions, and even without the query operators. The whole point of LINQ is that you have some integrated version of queries where you use compiler for sanity checks of them. The other crucial point is the unification of view at different datasources, whether it's a database or in-memory collection. You can live without LINQ, just as you can live without any other feature of the language and code in Assembler, but there are obvious advantages that are hard to oversee ;)

在没有扩展方法、lambda 表达式,甚至没有查询运算符的情况下,LINQ 语言功能集在 C# 2.0 代码中不是那么容易复制的。LINQ 的全部意义在于您有一些集成版本的查询,您可以在其中使用编译器对它们进行完整性检查。另一个关键点是统一不同数据源的视图,无论是数据库还是内存中的集合。你可以没有 LINQ,就像你可以在没有汇编语言和代码的任何其他特性的情况下生活一样,但是有一些明显的优势很难监督;)

回答by dxh

You're right, it's rarely very hard to replicate the features in regular C#. It is what they call syntactic sugar. It's just about convenience. You know about automatic properties? The ones that allow you to write public class User { public int Id { get; set; } }That's extremelyeasy to replicate in "regular" C# code. Even so, automatic properties are still awesome ;)

您说得对,在常规 C# 中复制这些功能很少很难。这就是他们所说的语法糖。这只是为了方便。你知道自动属性吗?允许您编写的public class User { public int Id { get; set; } }那些在“常规”C# 代码中非常容易复制。即便如此,自动属性仍然很棒;)

Filtering and sorting are pretty much the core of LINQ. Consider you have a list of users, called, well, users, and you want to find the ones who have logged in today, and display them in order of most recently logged in. Before LINQ, you'd probably do something like create a new list, that you populate based on the original list, by iterating it, adding what meets the criteria, and then implementing some sort of IComparable. Now you can just do:

过滤和排序几乎是 LINQ 的核心。假设您有一个用户列表,名为 ,users,并且您想找到今天登录的用户,并按照最近登录的顺序显示它们。在 LINQ 之前,您可能会做一些类似创建新的列表,您根据原始列表填充,通过迭代它,添加符合条件的内容,然后实现某种IComparable. 现在你可以这样做:

users = users.Where(u => u.LastLoggedIn.Date = DateTime.Today)
             .OrderBy(u => u.LastLoggedIn).ToList();

Convenience =)

方便=)

回答by Taylor Leese

The book Essential LINQprovides a great one paragraph summary of the benefit of LINQ:

Essential LINQ一书对 LINQ 的好处进行了精彩的一段总结:

LINQ does more than simply add new features to the language. It introduces a delcarative style of programming into the C# language. The declarative programming model allows developers to craft code that succictly captures their intent, without forcing them to worry about the order in which events take place, or their precise implementation. It allows developers to state what they want to do, rather than how it will be done.

LINQ 不仅仅是为语言添加新功能。它在 C# 语言中引入了一种声明式的编程风格。声明式编程模型允许开发人员编写代码以简洁地捕捉他们的意图,而不必强迫他们担心事件发生的顺序或它们的精确实现。它允许开发人员陈述他们想要做什么,而不是如何完成。

回答by Robert Harvey

Have a look at any of the many answers that Jon Skeet provides to Linq questions and you will see how versatile and useful Linq really is.

看看 Jon Skeet 为 Linq 问题提供的众多答案中的任何一个,您就会看到 Linq 真正的多功能性和有用性。

https://stackoverflow.com/search?q=user:22656+[linq]

https://stackoverflow.com/search?q=user:22656+[linq]