2016-04-20 36 views
0

我的样本数据coloumn,它来自一个CSV文件如何拆分并在列表中获得不同的单词?

|----Category------------| 

SHOES 
SHOES~SHOCKS 
SHOES~SHOCKS~ULTRA SOCKS 

我很想拆分特定列,并获得不同的值列表中的像

SHOES 
SHOCKS 
ULTRA SOCKS 

我尝试以下,但它不能按预期工作。

var test = from c in products select c.Category.Split('~').Distinct().ToList(); 

它实际上返回以下内容。

enter image description here

有什么想法吗?谢谢。

回答

1

您可以使用SelectMany扁平化集合:删除重复之前

products.SelectMany(p => p.Category.Split('~')).Distinct().ToList(); 
2

我会用SelectMany“平坦”的名单:

products.SelectMany(c => c.Category.Split('~')) 
     .Distinct() 
1

你被关闭,你只需要拼合通过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(); 

可以see a complete working example demonstrated here及下方观察:

// 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(); 
1

合并此列表的list of strings到一个列表使用SelectMany(),并只需要添加另外清晰到你的列表..

var test = from c in products select c.Category.Split('~').Distinct().ToList().SelectMany(x => x).Distinct().ToList();

1

这里是如何你会用查询语法来做。

var test = (from p in products 
      from item in p.Category.Split('~') 
      select item).Distinct().ToList(); 
相关问题