2016-04-20 32 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(); 
相關問題