C#代码描述需要帮助 [英] c# code description need help
本文介绍了C#代码描述需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码,但实际上我并不理解这里发生的事情,任何人都可以向我解释一下代码:
hi I have this code but in fact I dont understant what happen here can any one explain me the code :
ordering.GroupBy(name=> name).OrderByDescending(g => g.Count())
我不理解(name=>name)
和(g=>g.count)
仅在这部分中对我有帮助
I dont understand (name=>name)
and (g=>g.count)
help me only in this part
推荐答案
您可能会通过以下内容更好地理解这一点
name => name
与f(name) = name
相同,只是您不需要包括函数名称(在这种情况下,函数名称为f
)
因此,第一个ordering.GroupBy(name => name)
表示您希望分组符合名称.现在,此代码创建了一个键,在这种情况下,键仅具有name
以及具有相同name
的记录(对象)的集合.
在第二部分中发生的是,您正在对每个记录下的记录进行计数,这些记录是具有相同键或在这种情况下具有相同字符串的原始记录的集合.作为功能,这将是f(keyCollection) = keyCollection.Count()
.
这可能会有所帮助:
定义一个类:
You might understand this better by the following
name => name
is the same asf(name) = name
, just that you do not need to include a function name (in this care the function name isf
)
Therefore the firstordering.GroupBy(name => name)
is saying that you want the grouping to be according the the name. Now this code creates a key that in this case only has thename
and a collection of records (objects) that have the samename
.
What is happening in the second part is that you are counting the records under each record which is a collection of original records that have the same key, or in this case are the same string. As a function this would bef(keyCollection) = keyCollection.Count()
.
This might help:
Define a class:
public class t
{
public string Shortname { get; set; }
public string Longname { get; set; }
}
然后将其放在控制台程序中:
Then put this in a console program:
var testclass = new t[] {new t {Shortname = "US", Longname = "Long US 1"},
new t {Shortname = "US", Longname = "Long US 2"},
new t {Shortname = "UK", Longname = "Long UK 1"},};
var testLinq = testclass.GroupBy(i => i.Shortname);
foreach (var g in testLinq)
{
Console.WriteLine("Key = " + g.Key);
Console.WriteLine(" Records");
foreach (var r in g)
Console.WriteLine(" " + r.Longname);
Console.WriteLine();
}
Console.ReadLine();
您将获得以下内容:
You will get the following:
Key = US
Records
Long US 1
Long US 2
Key = UK
Records
Long UK 1
这很好文章它如何在C#? -第3部分(详细介绍了C#LINQ) [
This is a nice article How does it work in C#? - Part 3 (C# LINQ in detail)[^]
Please read it and it will help you.
Thanks
那些是lambdas,
Those are lambdas,
name => name
将name
作为参数并返回name
Takes name
as an argument and returns name
g => g.count
将g
作为参数并返回g.Count()
因此,它按名称将它们分组,然后按每个组中的项目数对其进行排序.
Takes g
as an argument and returns g.Count()
So it groups them by name, then orders them by the number of items in each group.
这篇关于C#代码描述需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文