2017-01-15 5 views
0

SCENARIO使用してリストの一覧から重複を削除します。はどのようにLINQの

問題:

問題は、次の論理が重複回避するが、ID 4および1行はbasketリストに追加されないように、いくつかの行を追加しない、ということです。

QUESTION:

  • 誰かが間違っているかどうか確認してくださいもらえますか?
  • 同じことを達成するためのより良い方法はありますか?

(テキストファイル: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

List of Listを使用する代わりに、1つのListだけではなく、そこから複製をチェックするのはなぜですか?あなたは代わりにこれを行うことはできません。

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

を次に、あなたのwhile文で:

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

DuplicateItem静的メソッドを追加する必要が。

関連する問題