2017-01-15 22 views
0

方案中刪除重複。如何從列表的列表使用LINQ

問題:

的問題是,下面的邏輯避免了重複的,但不與ID 4添加像的行某些行和1不添加到basket列表。

問題:

  • 可能有人請檢查出了什麼問題?
  • 有沒有更好的方法來實現同樣的事情?

(文本文件:的abc.txt)

ID ITEM QTY SOURCE 
2 Banana 4 tree 
3 Milk 3 animal 
5 Creme 2 animal 
2 Banana 4 tree 
3 Milk 3 animal 
10 Banana 4 tree 
4 Milk 3 animal 
5 Creme 2 animal 
1 Banana 4 tree 
32 Milk 3 animal 

(代碼)

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<List<string>> basket = new List<List<string>>(); 
      var filePath = @"c:\temp\abc.txt"; 
      using (StreamReader stream = new StreamReader(filePath)) 
      { 
       while (!stream.EndOfStream) 
       { 
        var lineContents = stream.ReadLine().Split('\t'); 
        if (!DuplicateItem(basket, lineContents)) 
        { 
         basket.Add(lineContents.ToList()); 
        } 
       } 
      } 
      Console.Read(); 
     } 

     private static bool DuplicateItem(List<List<string>> basket, string[] line) 
     { 
      return basket.Exists(row => row.Exists(col => col.ElementAt(0).ToString().Equals(line[0]))) ? true : false; 
     } 
    } 
} 
+0

目前尚不清楚你的案件中* duplicate *的定義是什麼。例如,它是僅基於「ID」列值還是所有列值或其他值? –

回答

0

你的ID的存在性的檢查是無效的,因爲你正在檢查的ID的第一個字符與新行的字符串ID相等的行。 (這就是爲什麼還需要使用ToString)。你可以簡化你的邏輯,如:

private static bool DuplicateItem(List<List<string>> basket, string[] line) 
{ 
    return basket.Exists(row => row[0] == line[0]); 
} 
0

而不是使用列表清單,爲什麼不只是一個列表,並從那裏檢查重複?您while語句

IList<string> basket = new List<string>(); 

然後......你可以做到這一點,而不是

if (!basket.Contains(lineContents[0].ToString())) 
basket.Add(lineContents[0].ToString()); 

無需添加DuplicateItem靜態方法。