如何使用c#中具有相同值计数的返回列表计算List中的Distinct [英] How to count Distinct in List with return list with same value count in c#
本文介绍了如何使用c#中具有相同值计数的返回列表计算List中的Distinct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
我的行数据是
string [] filePaths1 = { 7.1, 7.1, 7.2, < span class =code-string> 7.2, 7.3, 7.4};
我需要一个linq查询,它会给我列出包含唯一数据的列表。
例如:
7.1 => 2
7.2 => 2
7.3 => 1
7.4 => 1
谢谢,
解决方案
例如使用Linq:
< pre lang =c#> string [] filePaths1 = { 7.1, 7.1, 7.2, 7.2 , 7.3, 7.4};
var qry = 来自 s in filePaths1
group s by s into grp
< span class =code-sdkkeyword> select new {
num = grp.Key,
count = grp.Count( )
};
// 然后......
foreach ( var o in qry)
{
Console.WriteLine( {0} - > {1},o.num,o。计数);
}
使用通用字典< string,int> 。迭代原始列表,使用 ContainsKey()将每个条目与字典进行比较方法。尚不存在的密钥,使用添加字典中的新条目(whateverString,1),现有的密钥只是使用 YourDictionary [whateverString] ++
增加它们的价值你可以做像这样:
string [] filePaths1 = { 7.1, 7.1, 7.2, 7.2, 7.3, 7.4};
List< string> distinctFilePaths = filePaths1.Distinct()。ToList();
foreach ( string filePath in distinctFilePaths)
{
int count = filePaths1.Count(x = > ; x == filePath);
}
Hi,
For Example:
My Row data is
string[] filePaths1 = { "7.1", "7.1", "7.2", "7.2", "7.3", "7.4" };
I need a linq query that will give me the list of list with the number of unique data.
For example:
7.1 => 2
7.2 => 2
7.3 => 1
7.4 => 1
Thanks,
解决方案
For example using Linq:
string[] filePaths1 = { "7.1", "7.1", "7.2", "7.2", "7.3", "7.4" }; var qry = from s in filePaths1 group s by s into grp select new{ num = grp.Key, count = grp.Count() }; //then... foreach(var o in qry) { Console.WriteLine("{0} -> {1}", o.num, o.count); }
Use a generic Dictionary<string, int>. Iterate over the original list, comparing every entry with the dictionary using the ContainsKey() method. Keys that don't exist yet, get a new entry in the dictionary with Add(whateverString, 1), existing keys just increase their value using YourDictionary[whateverString]++
You could do like this:
string[] filePaths1 = { "7.1", "7.1", "7.2", "7.2", "7.3", "7.4" }; List<string> distinctFilePaths = filePaths1.Distinct().ToList(); foreach(string filePath in distinctFilePaths) { int count = filePaths1.Count(x => x == filePath); }
这篇关于如何使用c#中具有相同值计数的返回列表计算List中的Distinct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文