我应该在什么时候使用LINQ ?

时间:2022-05-09 20:52:27

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!

谢谢!

15 个解决方案

#1


18  

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 (Distance is the Levenshtein edit distance of the matching model's unique id from the uniqueID parameter).

这是一个对存储库、订单进行搜索的代码片段,并将前10个匹配的业务对象转换为特定于视图的模型(距离是匹配模型唯一id的Levenshtein编辑距离,来自unique eid参数)。

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

#2


15  

It depends on what kind of linq you mean.

这取决于你指的是哪种林q。

Is it linq-to-sql? In that case, it's an orm with all the same benefits that come from using any other orm. I don't use it much and can't really say more.

linq to sql吗?在这种情况下,它是一个orm,具有使用其他orm所带来的所有好处。我不怎么用它,也说不出更多。

Is it linq-to-objects? In that case, you're really talking about a collection of other things: extension methods, lazy iterators, and a query comprehension syntax. It's an introduction into the world of functional programming. I don't have much use for the query comprehension syntax, but for the rest, I can best demonstrate with an example.

linq-to-objects吗?在这种情况下,您实际上是在讨论其他东西的集合:扩展方法、惰性迭代器和查询理解语法。这是对函数式编程世界的介绍。我对查询理解语法没有太多用处,但是对于其余的部分,我可以用一个示例进行最好的演示。

Let's say you want to read a file in line by line. For each line, you want to check if it meets some criteria, convert a portion of those lines to an integer, and sum up the first 10 of those integers that are also within a certain range. Here's the old way you would do that:

假设要逐行读取文件。对于每一行,您需要检查它是否满足某些条件,将这些行的一部分转换成整数,并对在一定范围内的前10个整数进行求和。这是你的老方法:

int SumXValues(string filename)
{
    string line;
    int sum = 0;
    int count = 0;
    using (var rdr = new StreamReader(filename))
    {

        while ( (line = rdr.ReadLine()) != null && count < 10)
        {
           int val;
           if (int.TryParse(line.Substring(3,3))
           {
               if (val > 4 && val < 25)
               {
                    sum += val;
                    count ++;
               }
            }
        }
    }
    return sum;
}

Here's the new way:

这是新方法:

IEnumerable<string> ReadLines(string filename)
{
    string line;
    using (var rdr = new StreamReader(filename))
        while ( (line = rdr.ReadLine()) != null)
           yield return line;
}

int SumXValues(string filename)
{
    return ReadLines(filename)
               .Select(l => l.Substring(3,3))
               .Where(l => int.TryParse(l))
               .Select(i => int.Parse(i))
               .Where(i => i > 4 && i < 16)
               .Take(10)
               .Sum(i => i);
}

Notice the new code is actually shorter. But why is it also better? There are (at least) 4 reasons:

注意,新代码实际上更短。但为什么它也更好呢?有(至少)4个原因:

  • Hopefully it's obvious how re-usable the readlines function is. You could factor out more as well, but the point is to show how this style helps you re-use more code.
  • 很明显,readlines函数的可重用性是显而易见的。您也可以提出更多的内容,但重点是展示这种风格如何帮助您重用更多的代码。
  • It scales better. Notice all the chained function calls in that last function. You know how many times that code will iterator over the lines in your file? Exactly once! In fact, not even that long as it will stop reading from the file after taking the first 10 items. And if you change it to return an enumerable and then use that elsewhere with other extension methods? Still just once! This lets you build, mix, and re-mix your query results at runtime without costly additional passes on your lists.
  • 伸缩性好一点。注意最后一个函数中的所有链式函数调用。您知道该代码在文件中的行上迭代多少次?完全一次!事实上,即使是在获取前10项之后,它也不会停止从文件中读取数据。如果你改变它来返回一个可枚举,然后在其他的扩展方法中使用它?还是只有一次!这使您可以在运行时构建、混合和重新混合查询结果,而无需对列表进行昂贵的附加传递。
  • It's more maintainable. If the criteria changes, it's easy to spot the the exact "rule" (if you will) that you care about and modify just that part.
  • 这是更易于维护。如果标准发生变化,很容易发现您所关心的确切的“规则”(如果愿意的话),并对其进行修改。
  • It's more readable. This allows you to express the code in terms of what it is doing rather than how it does it.
  • 它是更具可读性。这使您可以根据代码正在做什么而不是如何做来表达代码。

#3


12  

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也可以用于数据库,但是我发现我并没有这么做。我猜是为了他/她自己。

#4


10  

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

《基本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#语言中引入了一种delcarative编程风格。声明性编程模型允许开发人员手工编写代码,以成功地捕捉他们的意图,而不必担心事件发生的顺序,或者他们的精确实现。它允许开发人员声明他们想做什么,而不是如何去做。

#5


6  

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 extremely easy to replicate in "regular" C# code. Even so, automatic properties are still awesome ;)

您是对的,在常规c#中复制这些特性很少是很难的。这就是他们所说的句法糖。这只是方便。你知道自动属性吗?允许您编写公共类用户{public int Id {get;设置;这在“常规”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之前,您可能要做一些事情,比如创建一个新的列表,在原始列表的基础上填充它,通过迭代它,添加符合条件的内容,然后实现某种icom亦有道。现在你可以这样做:

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

Convenience =)

方便=)

#6


4  

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数据集来处理数据。DataTables是一个通用的数据存储库,我经常在其中存储来自已加载的CSV文件的值。使用LINQ查询或连接数据,而不是使用for循环的“蛮力”-ing,这样更易于阅读和使用。

#7


3  

I would turn the question around: can you show us how you would emulate Linq features without it? I'm having trouble thinking of a case where it isn't an immense help.

我想反过来问:如果没有它,您能向我们展示如何模仿Linq特性吗?我想不出一个案子对我没有多大帮助。

For example, I saw something like this recently:

例如,我最近看到了这样的事情:

foreach (var person in people.OrderBy(p => p.Company)
                             .ThenBy(p => p.LastName)
                             .ThenBy(p => p.FirstName)) {
    ...
}

I guess it could have used Arrays.Sort, created a delegate that checked the fields in the right order (backwards from written, right?), and then just lived with the fact that it would only ever work on Arrays. That seems like it would be a lot longer, harder to maintain, and less flexible.

我想它可以用数组。排序,创建一个以正确的顺序检查字段的委托(从书写开始向后,对吧?这似乎需要更长的时间,更难维护,更不灵活。

#8


2  

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来使用可选代码的对象,这并不难。我倾向于喜欢lambda表达式的语义,而且它确实将几行代码打包成一行代码。但是,您可以使用自己的代码进行许多操作,除了一些较大的操作(union、intersect等)更容易使用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到实体)是一个对象关系映射器,可以映射到数据库表,并充当存储过程和ADO。NET数据集就是这样,所以这是一个非常好的替代方法,比弱数据集/数据表更好,我也喜欢强类型的数据集/表。

HTH.

HTH。

#9


2  

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://*.com/search?q=user:22656+[linq]

https://*.com/search?q=user:22656 +(linq)

#10


1  

Take a look at ReSharper if you haven't already. It has a lot of hints for "... convert to LINQ syntax" so it can usually show you a thing or two you didn't consider when learning. :)

如果你还没看过ReSharper,看看吧。它有很多暗示……转换到LINQ语法“因此它通常可以向您展示一些您在学习时没有考虑到的东西。:)

#11


1  

Somebody mentioned that LINQ is a declarative style of programming. I just wanted to expand on that.

有人提到LINQ是一种声明式编程风格。我只是想扩展一下。

One way I use LINQ is to write test oracle code. It's very important that the test code be simple and as close to "obviously correct" as possible, or else it will end up with as many bugs as the code that it's supposed to test. With one particular feature that I'm testing now, I wrote out a small list of set comprehensions that describe exactly how I expect the feature to work. Thanks to LINQ, converting those comprehensions to code becomes trivially easy:

我使用LINQ的一种方法是编写测试oracle代码。最重要的是,测试代码要尽可能简单,并尽可能接近“明显正确”,否则,它最终将产生与它应该测试的代码一样多的bug。我现在正在测试的一个特定特性,列出了一小部分集合理解,它们准确地描述了我对该特性的期望。由于LINQ,将这些理解转换为代码变得非常简单:

A = all items
B = [x in A: x.Type = selectedtype, x.Source = "sourceA"]
C = [x in A: x.Source = "sourceB"]
D = B union C

In code:

在代码:

IEnumerable<MyClass> SetB(IEnumerable<MyClass> allItems, MyType type)
{
  var result = from item in allItems
               where item.Type == type && item.Source == "sourceA"
               select item;
  return result;
}

IEnumerable<MyClass> SetC(IEnumerable<MyClass> allItems)
{
  var result = from item in allItems
               where item.Source == "sourceB"
               select item;
  return result;
}

IEnumerable<MyClass> SetD(IEnumerable<MyClass> allItems, MyType type)
{
  var setB = SetB(allItems, type);
  var setC = SetC(allItems);
  return setB.Union(setC);
}

While still quite a bit more verbose than the mathematical expressions, it's much simpler and easier to call "obviously correct" than imperative code would be. The LINQ code is declarative like the math is declarative. Less translation, closer to the spec. LINQ, when used appropriately, is pretty much a "Do what I mean" language.

虽然仍然比数学表达式要冗长一些,但是与命令式代码相比,调用“显然正确”要简单得多,也更容易。LINQ代码是声明性的,就像数学是声明性的一样。更少的翻译,更接近于规范。

Note that I wouldn't write the actual code this way. Performance is not a requirement for test code, but it is for the real code, so the real code still needs to be a SQL stored procedure.

注意,我不会以这种方式编写实际的代码。性能不是测试代码的要求,但它是真正的代码,所以真正的代码仍然需要是一个SQL存储过程。

#12


0  

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

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

#13


0  

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

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

#14


0  

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 ;)

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

#15


0  

One more point to add to all that is a kind of summary point. You can see from above that it's used for convenience and succinctness and can be used with collections, SQL, XML (and anything else that cares to implement a LINQ provider), but best of all you only have to learn the LINQ syntax once and it carries across into all those useful technology areas.

还有一点要补充的是,这是一种总结。从上面你可以看到,它是用于方便和简洁,可以用于收藏,SQL、XML(和其他关心实现LINQ提供程序),但最重要的是你只需要学习LINQ语法一旦和它携带到所有那些有用的技术领域。

#1


18  

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 (Distance is the Levenshtein edit distance of the matching model's unique id from the uniqueID parameter).

这是一个对存储库、订单进行搜索的代码片段,并将前10个匹配的业务对象转换为特定于视图的模型(距离是匹配模型唯一id的Levenshtein编辑距离,来自unique eid参数)。

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

#2


15  

It depends on what kind of linq you mean.

这取决于你指的是哪种林q。

Is it linq-to-sql? In that case, it's an orm with all the same benefits that come from using any other orm. I don't use it much and can't really say more.

linq to sql吗?在这种情况下,它是一个orm,具有使用其他orm所带来的所有好处。我不怎么用它,也说不出更多。

Is it linq-to-objects? In that case, you're really talking about a collection of other things: extension methods, lazy iterators, and a query comprehension syntax. It's an introduction into the world of functional programming. I don't have much use for the query comprehension syntax, but for the rest, I can best demonstrate with an example.

linq-to-objects吗?在这种情况下,您实际上是在讨论其他东西的集合:扩展方法、惰性迭代器和查询理解语法。这是对函数式编程世界的介绍。我对查询理解语法没有太多用处,但是对于其余的部分,我可以用一个示例进行最好的演示。

Let's say you want to read a file in line by line. For each line, you want to check if it meets some criteria, convert a portion of those lines to an integer, and sum up the first 10 of those integers that are also within a certain range. Here's the old way you would do that:

假设要逐行读取文件。对于每一行,您需要检查它是否满足某些条件,将这些行的一部分转换成整数,并对在一定范围内的前10个整数进行求和。这是你的老方法:

int SumXValues(string filename)
{
    string line;
    int sum = 0;
    int count = 0;
    using (var rdr = new StreamReader(filename))
    {

        while ( (line = rdr.ReadLine()) != null && count < 10)
        {
           int val;
           if (int.TryParse(line.Substring(3,3))
           {
               if (val > 4 && val < 25)
               {
                    sum += val;
                    count ++;
               }
            }
        }
    }
    return sum;
}

Here's the new way:

这是新方法:

IEnumerable<string> ReadLines(string filename)
{
    string line;
    using (var rdr = new StreamReader(filename))
        while ( (line = rdr.ReadLine()) != null)
           yield return line;
}

int SumXValues(string filename)
{
    return ReadLines(filename)
               .Select(l => l.Substring(3,3))
               .Where(l => int.TryParse(l))
               .Select(i => int.Parse(i))
               .Where(i => i > 4 && i < 16)
               .Take(10)
               .Sum(i => i);
}

Notice the new code is actually shorter. But why is it also better? There are (at least) 4 reasons:

注意,新代码实际上更短。但为什么它也更好呢?有(至少)4个原因:

  • Hopefully it's obvious how re-usable the readlines function is. You could factor out more as well, but the point is to show how this style helps you re-use more code.
  • 很明显,readlines函数的可重用性是显而易见的。您也可以提出更多的内容,但重点是展示这种风格如何帮助您重用更多的代码。
  • It scales better. Notice all the chained function calls in that last function. You know how many times that code will iterator over the lines in your file? Exactly once! In fact, not even that long as it will stop reading from the file after taking the first 10 items. And if you change it to return an enumerable and then use that elsewhere with other extension methods? Still just once! This lets you build, mix, and re-mix your query results at runtime without costly additional passes on your lists.
  • 伸缩性好一点。注意最后一个函数中的所有链式函数调用。您知道该代码在文件中的行上迭代多少次?完全一次!事实上,即使是在获取前10项之后,它也不会停止从文件中读取数据。如果你改变它来返回一个可枚举,然后在其他的扩展方法中使用它?还是只有一次!这使您可以在运行时构建、混合和重新混合查询结果,而无需对列表进行昂贵的附加传递。
  • It's more maintainable. If the criteria changes, it's easy to spot the the exact "rule" (if you will) that you care about and modify just that part.
  • 这是更易于维护。如果标准发生变化,很容易发现您所关心的确切的“规则”(如果愿意的话),并对其进行修改。
  • It's more readable. This allows you to express the code in terms of what it is doing rather than how it does it.
  • 它是更具可读性。这使您可以根据代码正在做什么而不是如何做来表达代码。

#3


12  

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也可以用于数据库,但是我发现我并没有这么做。我猜是为了他/她自己。

#4


10  

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

《基本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#语言中引入了一种delcarative编程风格。声明性编程模型允许开发人员手工编写代码,以成功地捕捉他们的意图,而不必担心事件发生的顺序,或者他们的精确实现。它允许开发人员声明他们想做什么,而不是如何去做。

#5


6  

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 extremely easy to replicate in "regular" C# code. Even so, automatic properties are still awesome ;)

您是对的,在常规c#中复制这些特性很少是很难的。这就是他们所说的句法糖。这只是方便。你知道自动属性吗?允许您编写公共类用户{public int Id {get;设置;这在“常规”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之前,您可能要做一些事情,比如创建一个新的列表,在原始列表的基础上填充它,通过迭代它,添加符合条件的内容,然后实现某种icom亦有道。现在你可以这样做:

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

Convenience =)

方便=)

#6


4  

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数据集来处理数据。DataTables是一个通用的数据存储库,我经常在其中存储来自已加载的CSV文件的值。使用LINQ查询或连接数据,而不是使用for循环的“蛮力”-ing,这样更易于阅读和使用。

#7


3  

I would turn the question around: can you show us how you would emulate Linq features without it? I'm having trouble thinking of a case where it isn't an immense help.

我想反过来问:如果没有它,您能向我们展示如何模仿Linq特性吗?我想不出一个案子对我没有多大帮助。

For example, I saw something like this recently:

例如,我最近看到了这样的事情:

foreach (var person in people.OrderBy(p => p.Company)
                             .ThenBy(p => p.LastName)
                             .ThenBy(p => p.FirstName)) {
    ...
}

I guess it could have used Arrays.Sort, created a delegate that checked the fields in the right order (backwards from written, right?), and then just lived with the fact that it would only ever work on Arrays. That seems like it would be a lot longer, harder to maintain, and less flexible.

我想它可以用数组。排序,创建一个以正确的顺序检查字段的委托(从书写开始向后,对吧?这似乎需要更长的时间,更难维护,更不灵活。

#8


2  

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来使用可选代码的对象,这并不难。我倾向于喜欢lambda表达式的语义,而且它确实将几行代码打包成一行代码。但是,您可以使用自己的代码进行许多操作,除了一些较大的操作(union、intersect等)更容易使用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到实体)是一个对象关系映射器,可以映射到数据库表,并充当存储过程和ADO。NET数据集就是这样,所以这是一个非常好的替代方法,比弱数据集/数据表更好,我也喜欢强类型的数据集/表。

HTH.

HTH。

#9


2  

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://*.com/search?q=user:22656+[linq]

https://*.com/search?q=user:22656 +(linq)

#10


1  

Take a look at ReSharper if you haven't already. It has a lot of hints for "... convert to LINQ syntax" so it can usually show you a thing or two you didn't consider when learning. :)

如果你还没看过ReSharper,看看吧。它有很多暗示……转换到LINQ语法“因此它通常可以向您展示一些您在学习时没有考虑到的东西。:)

#11


1  

Somebody mentioned that LINQ is a declarative style of programming. I just wanted to expand on that.

有人提到LINQ是一种声明式编程风格。我只是想扩展一下。

One way I use LINQ is to write test oracle code. It's very important that the test code be simple and as close to "obviously correct" as possible, or else it will end up with as many bugs as the code that it's supposed to test. With one particular feature that I'm testing now, I wrote out a small list of set comprehensions that describe exactly how I expect the feature to work. Thanks to LINQ, converting those comprehensions to code becomes trivially easy:

我使用LINQ的一种方法是编写测试oracle代码。最重要的是,测试代码要尽可能简单,并尽可能接近“明显正确”,否则,它最终将产生与它应该测试的代码一样多的bug。我现在正在测试的一个特定特性,列出了一小部分集合理解,它们准确地描述了我对该特性的期望。由于LINQ,将这些理解转换为代码变得非常简单:

A = all items
B = [x in A: x.Type = selectedtype, x.Source = "sourceA"]
C = [x in A: x.Source = "sourceB"]
D = B union C

In code:

在代码:

IEnumerable<MyClass> SetB(IEnumerable<MyClass> allItems, MyType type)
{
  var result = from item in allItems
               where item.Type == type && item.Source == "sourceA"
               select item;
  return result;
}

IEnumerable<MyClass> SetC(IEnumerable<MyClass> allItems)
{
  var result = from item in allItems
               where item.Source == "sourceB"
               select item;
  return result;
}

IEnumerable<MyClass> SetD(IEnumerable<MyClass> allItems, MyType type)
{
  var setB = SetB(allItems, type);
  var setC = SetC(allItems);
  return setB.Union(setC);
}

While still quite a bit more verbose than the mathematical expressions, it's much simpler and easier to call "obviously correct" than imperative code would be. The LINQ code is declarative like the math is declarative. Less translation, closer to the spec. LINQ, when used appropriately, is pretty much a "Do what I mean" language.

虽然仍然比数学表达式要冗长一些,但是与命令式代码相比,调用“显然正确”要简单得多,也更容易。LINQ代码是声明性的,就像数学是声明性的一样。更少的翻译,更接近于规范。

Note that I wouldn't write the actual code this way. Performance is not a requirement for test code, but it is for the real code, so the real code still needs to be a SQL stored procedure.

注意,我不会以这种方式编写实际的代码。性能不是测试代码的要求,但它是真正的代码,所以真正的代码仍然需要是一个SQL存储过程。

#12


0  

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

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

#13


0  

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

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

#14


0  

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 ;)

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

#15


0  

One more point to add to all that is a kind of summary point. You can see from above that it's used for convenience and succinctness and can be used with collections, SQL, XML (and anything else that cares to implement a LINQ provider), but best of all you only have to learn the LINQ syntax once and it carries across into all those useful technology areas.

还有一点要补充的是,这是一种总结。从上面你可以看到,它是用于方便和简洁,可以用于收藏,SQL、XML(和其他关心实现LINQ提供程序),但最重要的是你只需要学习LINQ语法一旦和它携带到所有那些有用的技术领域。