C# 我是否缺少有关 LINQ 的某些信息?

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

Am I missing something about LINQ?

提问by Jason Baker

I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.

我似乎缺少关于 LINQ 的一些东西。对我来说,它看起来像是将一些我最不喜欢的 SQL 元素移到 C# 语言中,并将它们用于其他用途。

I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?

我的意思是,我可以看到在数据库以外的事物上使用类似 SQL 的语句的好处。但是,如果我想编写 SQL,那么为什么不直接编写 SQL 并将其排除在 C# 之外呢?我在这里缺少什么?

采纳答案by FlySwat

LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.

LINQ 与 SQL 无关。LINQ 是关于在对象上应用函数式编程范式。

LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.

LINQ to SQL 是建立在 LINQ 基础之上的 ORM,但 LINQ 远不止于此。我不使用 LINQ to SQL,但我一直使用 LINQ。

Take the task of finding the intersection of two lists:

采取寻找两个列表交集的任务:

Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code.

在 LINQ 之前,这个任务需要编写一个嵌套的 foreach,为大列表中的每个项目迭代一次小列表 O(N*M),大约需要 10 行代码。

foreach (int number in list1)
{
    foreach (int number2 in list2)
    {
        if (number2 == number)
        {
            returnList.add(number2);
        }
    }
}

Using LINQ, it does the same thing in one line of code:

使用 LINQ,它在一行代码中做同样的事情:

var results = list1.Intersect(list2);

You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.

您会注意到它看起来不像 LINQ,但它确实如此。如果您不想,则不需要使用表达式语法。

回答by TheSmurf

The point is that LINQ integrates your queries into your primary programming language, allowing your IDE to provide you with some facilities (Intellisense and debug support, for example) that you otherwise would not have, and to allow the compiler to type-check your SQL code (which is impossible with a normal string query).

关键是 LINQ 将您的查询集成到您的主要编程语言中,允许您的 IDE 为您提供一些您本来不会拥有的设施(例如智能感知和调试支持),并允许编译器对您的 SQL 进行类型检查代码(使用普通字符串查询是不可能的)。

回答by ScottKoon

So the really, really big deal about LINQ has nothing to do with Linq to SQL. It's about the enhancements it brought to the C# language itself.

所以关于 LINQ 的真正非常重要的事情与 Linq to SQL 无关。它是关于它给 C# 语言本身带来的增强。

回答by Wedge

LINQ is not just an ORM system, as Jonathan pointed out it brings a lot of functional programming elements to C#. And it lets you do a lot of "database-y" things in regular C# code. It's difficult to explain just how incredibly powerful that can be. Consider how much having solid, well designed generic data structures (such as list, stack, dictionary/hash, etc.) included in common frameworks has improved the state of development in modern languages. Precisely because using these data structures is very common and reducing the intellectual overhead of using them is a huge benefit. LINQ doesn't do anything you can't do yourself, but it makes a lot of operations a lot more straightforward and a lot easier.

LINQ 不仅仅是一个 ORM 系统,正如 Jonathan 指出的那样,它为 C# 带来了许多函数式编程元素。它允许您在常规 C# 代码中执行许多“与数据库相关”的事情。很难解释它有多么强大。考虑一下通用框架中包含的可靠、设计良好的通用数据结构(例如列表、堆栈、字典/哈希等)在多大程度上改善了现代语言的开发状态。正是因为使用这些数据结构非常普遍,减少使用它们的智力开销是一个巨大的好处。LINQ 不会做任何你自己不能做的事情,但它让很多操作变得更加直接和容易。

Consider the time-honored example of removing duplicates from a non-ordered list. In a lower level language like C or C++ you'd probably have to sort the list and maintain two indices into the list as you removed dupes. In a language with hashes (Java, C#, Javascript, Perl, etc.) you could create a hash where the keys are the unique values, then extract the keys into a new list. With LINQ you could just do this:

考虑从无序列表中删除重复项的历史悠久的示例。在像 C 或 C++ 这样的低级语言中,您可能必须在删除重复项时对列表进行排序并在列表中维护两个索引。在带有哈希的语言(Java、C#、Javascript、Perl 等)中,您可以创建一个哈希,其中键是唯一值,然后将键提取到一个新列表中。使用 LINQ,您可以这样做:

int[] data = { 0, 1, 3, 3, 7, 8, 0, 9, 2, 1 };

var uniqueData = data.GroupBy(i => i).Select(g => g.Key);

回答by Benjol

Before:

前:

// Init Movie
m_ImageArray = new Image[K_NB_IMAGE];

Stream l_ImageStream = null;
Bitmap l_Bitmap = null;

// get a reference to the current assembly
Assembly l_Assembly = Assembly.GetExecutingAssembly();

// get a list of resource names from the manifest
string[] l_ResourceName = l_Assembly.GetManifestResourceNames();

foreach (string l_Str in l_ResourceName)
{
    if (l_Str.EndsWith(".png"))
    {
        // attach to stream to the resource in the manifest
        l_ImageStream = l_Assembly.GetManifestResourceStream(l_Str);
        if (!(null == l_ImageStream))
        {
            // create a new bitmap from this stream and 
            // add it to the arraylist
            l_Bitmap = Bitmap.FromStream(l_ImageStream) as Bitmap;
            if (!(null == l_Bitmap))
            {
                int l_Index = Convert.ToInt32(l_Str.Substring(l_Str.Length - 6, 2));
                l_Index -= 1;
                if (l_Index < 0) l_Index = 0;
                if (l_Index > K_NB_IMAGE) l_Index = K_NB_IMAGE;
                m_ImageArray[l_Index] = l_Bitmap;
            }
            l_Bitmap = null;
            l_ImageStream.Close();
            l_ImageStream = null;
        } // if
    } // if
} // foreach

After:

后:

Assembly l_Assembly = Assembly.GetExecutingAssembly();

//Linq is the tops
m_ImageList = l_Assembly.GetManifestResourceNames()
    .Where(a => a.EndsWith(".png"))
    .OrderBy(b => b)
    .Select(c => l_Assembly.GetManifestResourceStream(c))
    .Where(d => d != null)  //ImageStream not null
    .Select(e => Bitmap.FromStream(e))
    .Where(f => f != null)  //Bitmap not null
    .ToList();

Or, alternatively (query syntax):

或者,或者(查询语法):

Assembly l_Assembly = Assembly.GetExecutingAssembly();

//Linq is the tops
m_ImageList = (
    from resource in l_Assembly.GetManifestResourceNames()
    where resource.EndsWith(".png")
    orderby resource
    let imageStream = l_Assembly.GetManifestResourceStream(resource)
    where imageStream != null
    let bitmap = Bitmap.FromStream(imageStream)
    where bitmap != null)
    .ToList();

回答by Jacob Stanley

Because linq is really monads in sql clothing, I'm using it on a project to make asynchronous web requests with the continuation monad, and it's proving to work really well!

因为 linq 确实是 sql 服装中的 monad,所以我在一个项目中使用它来通过 continuation monad 发出异步 Web 请求,事实证明它工作得非常好!

Check out these articles: http://www.aboutcode.net/2008/01/14/Async+WebRequest+Using+LINQ+Syntax.aspxhttp://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx

查看这些文章: http: //www.aboutcode.net/2008/01/14/Async+WebRequest+Using+LINQ+Syntax.aspx http://blogs.msdn.com/wesdyer/archive/2008/01/ 11/the-marvels-of-monads.aspx

From the first article:

从第一篇文章:

    var requests = new[] 
    {
        WebRequest.Create("http://www.google.com/"),
        WebRequest.Create("http://www.yahoo.com/"),
        WebRequest.Create("http://channel9.msdn.com/")
    };

    var pages = from request in requests
                select
                    from response in request.GetResponseAsync()
                    let stream = response.GetResponseStream()
                    from html in stream.ReadToEndAsync()
                    select new { html, response };

    foreach (var page in pages)
    {
        page(d =>
        {
            Console.WriteLine(d.response.ResponseUri.ToString());
            Console.WriteLine(d.html.Substring(0, 40));
            Console.WriteLine();
        });
    }