方案中刪除重複。如何從列表的列表使用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;
}
}
}
目前尚不清楚你的案件中* duplicate *的定義是什麼。例如,它是僅基於「ID」列值還是所有列值或其他值? –