要使用GroupBy()
进行此操作,您需要一个合适的IEqualityComparer<List<string>>
来比较字符串列表。没有内置的实现,因此您必须自己动手:
public sealed class StringListEqualityComparer : IEqualityComparer<List<string>>
{
public bool Equals(List<string> x,List<string> y)
{
if (ReferenceEquals(x,y))
return true;
if (x == null || y == null)
return false;
return x.SequenceEqual(y);
}
public int GetHashCode(List<string> strings)
{
int hash = 17;
foreach (var s in strings)
{
unchecked
{
hash = hash * 23 + s?.GetHashCode() ?? 0;
}
}
return hash;
}
}
一旦掌握了这些,就可以将其与GroupBy()
一起使用,如下所示:
public static void Main()
{
var sublist1 = new List<string>{ "a","b" };
var sublist2 = new List<string>{ "a","b" };
var sublist3 = new List<string>{ "a","c" };
var listOfLists = new List<List<string>> {sublist1,sublist2,sublist3};
var groups = listOfLists.GroupBy(item => item,new StringListEqualityComparer());
foreach (var group in groups)
{
Console.WriteLine($"Group: {string.Join(",",group.Key)},Count: {group.Count()}");
}
}
,
public JsonResult CountList(){
List<List<string>> d = new List<List<string>>(); //SuperList
d.Add(new List<string> { "a","b" }); //List 1
d.Add(new List<string> { "a","b" }); // List 2
d.Add(new List<string> { "a","c" }); // List 3
d.Add(new List<string> { "a","c","z" }); //List 4
var listCount = from items in d
group items by items.Aggregate((a,b)=>a+""+b) into groups
select new { groups.Key,Count = groups.Count() };
return new JsonResult(listCount);
}
这将提供以下结果作为Post Man或Advanced REST Client中的输出
[{
"key": "ab","count": 2
},{
"key": "ac","count": 1
},{
"key": "acz","count": 1
}],
,
我认为这会有所帮助
var list = new List<List<string>>() { sublist1,sublist3};
var result = list.GroupBy(x => string.Join(",x)).ToDictionary(x => x.Key.Split(',').ToList(),x => x.Count());
,
您可以尝试以下代码:-
List<string> sublist1 = new List<string>() { "a","b" };
List<string> sublist2 = new List<string>() { "a","b" };
List<string> sublist3 = new List<string>() { "a","c" };
List<List<string>> listOfLists = new List<List<string>> { sublist1,sublist3 };
Dictionary<string,int> counterDictionary = new Dictionary<string,int>();
foreach (List<string> strList in listOfLists)
{
string concat = strList.Aggregate((s1,s2) => s1 + "," + s2);
if (!counterDictionary.ContainsKey(concat))
counterDictionary.Add(concat,1);
else
counterDictionary[concat] = counterDictionary[concat] + 1;
}
foreach (KeyValuePair<string,int> keyValue in counterDictionary)
{
Console.WriteLine(keyValue.Key + "=>" + keyValue.Value);
}
,
我想我将通过以下方式解决此问题:
var equallists = list1.SequenceEqual(list2);
因此,我将不同的列表和具有SequenceEquals()的列表进行比较,并对它们进行计数。
欢迎使用更好的解决方案。 :)
本文链接:https://www.f2er.com/3118703.html