【发布时间】:2017-03-14 18:19:30
【问题描述】:
我有一个字符串列表,如下所示,我目前填写和分组如下:
public static List<CustomDTO> mostCommonKeywords { get; set; }
列表排序如下:
mostCommonKeywords = key.GroupBy(v2 => v2)
.Select(g => new CustomDTO { Key = g.Key, Count = g.Count() })
.OrderByDescending(e => e.Count).Distinct()
.ToList();
其中键是字符串列表,如下所示:
var key = new List<string>();
键列表中的每个字符串元素由 3 个单词组成,如果它们相等,我需要将它们合并为 1(或者将它们组合为一个,无论您更喜欢哪个术语)。
上面的分组方法给了我这些结果:
Samsung Galaxy S7
Galaxy S7 edge
Galaxy S7 Edge
S7 edge SM
Samsung Galaxy S7
Samsung Galaxy S7
您可以清楚地看到,此字符串列表中有重复项,我需要结果如下所示:
Samsung Galaxy S7
Galaxy S7 edge
S7 edge SM
所以基本上无论哪里出现相同的字符串,我都需要将它合并为一个......
我在这里做错了什么??
编辑:下面是 CustomDTO 类的样子:
public class CustomDTO
{
public string Key { get; set; }
public int Count { get; set; }
public List<int> Sales = new List<int>();
}
编辑:这里的事情是我在每个由 3 个单词组成的字符串中添加一个销售编号,以了解哪个关键字有多少销售......
这就是我的做法:
for (int i = 0; i < filtered.Count; i++)
{
foreach (var triad in GetAllWords(filtered[i]))
{
var sequence = triad[0] + " " + triad[1] + " " + triad[2];
key.Add(sequence + " " + lista[i].SaleNumber);
}
}
这是使字符串“不唯一”的部分:
+ lista[i].SaleNumber
编辑:
mostCommonKeywords 列表是 CustomDTO 对象的列表,其中包括:
public string Key { get; set; }
public int Count { get; set; }
public List<int> Sales = new List<int>();
并假设在所有内容的末尾,列表如下所示:
Key Sales
Samsung Galaxy S7 5
Galaxy S7 edge 4
Galaxy S7 Edge 4
S7 edge SM 3
Samsung Galaxy S7 6
Samsung Galaxy S7 7
我现在怎样才能找到所有这些重复项并将它们相加,以便列表如下所示:
Samsung galaxy S7 18
Galaxy S7 edge 8
S7 edge SM 3
【问题讨论】:
-
您是否尝试过使用 HashTable 而不是 List,或者调用 .Distinct()?
-
@rmjoia 我用 Distinct() 试过了,没用...还没试过 HashTable
-
你从哪里得到你的名单?数据库什么的?
-
我试过了,它应该可以正常工作。小提琴:dotnetfiddle.net/R7HVoO
标签: c# asp.net asp.net-mvc linq asp.net-mvc-5