[英]How can i split and get distinct words in a list?
My sample data coloumn, which come from an CSV file is 我的样本数据来自CSV文件,
|----Category------------|
SHOES
SHOES~SHOCKS
SHOES~SHOCKS~ULTRA SOCKS
I would love to split the specific column and get the distinct values in a list like 我想拆分特定的列,并在列表中获取不同的值,例如
SHOES
SHOCKS
ULTRA SOCKS
I tried the following, but it does not work as expected. 我尝试了以下操作,但是它没有按预期工作。
var test = from c in products select c.Category.Split('~').Distinct().ToList();
It actually returns the following. 它实际上返回以下内容。
Any thoughts please? 有什么想法吗? Thank you.
谢谢。
I would use SelectMany
to "flatten" the list before removing duplicates: 在删除重复项之前,我将使用
SelectMany
来“拉平”列表:
products.SelectMany(c => c.Category.Split('~'))
.Distinct()
您可以使用SelectMany
展平集合:
products.SelectMany(p => p.Category.Split('~')).Distinct().ToList();
You were close, you just needed to flatten out your collection to pull the individual items of each grouping via a SelectMany()
call : 亲密无间,您只需要展平集合即可通过
SelectMany()
调用提取每个分组的各个项目:
// The SelectMany will map the results of each of your Split() calls
// into a single collection (instead of multiple)
var test = products.SelectMany(p => p.Category.Split('~'))
.Distinct()
.ToList();
You can see a complete working example demonstrated here and seen below : 您可以在这里和下面看到一个完整的工作示例 :
// Example input
var input = new string[] { "SHOES","SHOES~SHOCKS","SHOES~SHOCKS~ULTRA SOCKS" };
// Get your results (yields ["SHOES","SHOCKS","ULTRA SOCKS"])
var output = input.SelectMany(p => p.Split('~'))
.Distinct()
.ToList();
通过使用SelectMany()
将此list of strings
列表list of strings
合并到一个列表中,然后向列表中添加另一个Distinct。
var test = from c in products select c.Category.Split('~').Distinct().ToList().SelectMany(x => x).Distinct().ToList();
Here's how you'd do it in query syntax. 这是您在查询语法中的处理方式。
var test = (from p in products
from item in p.Category.Split('~')
select item).Distinct().ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.