注册 登录
编程论坛 C# 论坛

如何删除csv表格中的重复行

wyh1988 发布于 2015-10-21 16:14, 1773 次点击
我有一个csv表格,如下:
只有本站会员才能查看附件,请 登录

我想实现这样的功能,通过第一列的数据来判断是否有重复项,如果有则删除重复项所在的行,最后得到的数据为
只有本站会员才能查看附件,请 登录

用C#语言怎么样实现啊,最好有详细的代码,谢谢各位了!
2 回复
#2
leisiege2015-10-22 15:35
读取一行,然后加入到list<string[]>列表中,然后读取下一行,如果list<string[]>中第一列contain读入数据的第一部分。这条数据就不加进去。就ok了。
#3
leisiege2015-10-22 15:50
程序代码:
namespace ConsoleApplication4
{
    class Program
    {
        static string path = @"C:\Users\鸣\Desktop\1111.csv";
        static void Main(string[] args)
        {
            
            if (File.Exists(path))
            {
                File.Delete(path);
                GenerateFIle();
            }
            List<string[]> content = new List<string[]>();

            ReadFile(content);
            int count = 0;
            foreach (var line in content)
            {
                count++;
                Console.WriteLine(line[0]+','+line[1]+"count:"+count);
            }
            Console.ReadKey();
               

           
            
        }

        private static void ReadFile(List<string[]> content)
        {
            using (StreamReader sr = new StreamReader(path))
            {
                while (true)
                {
                    var line = sr.ReadLine();
                    if (line == null)
                        break;
                    string[] words = line.Split(',');
                    List<string> firstline = content.Select(p => p[0]).ToList();
                    if (!firstline.Contains(words[0]))
                    {
                        content.Add(words);
                    }
                }
            }
        }

        private static void GenerateFIle()
        {
            using (StreamWriter sw = new StreamWriter(path))
            {
                var count = 0;
                Random rnd = new Random();
                for (var i = 0; i < 100; i++)
                {
                    count++;
                    sw.WriteLine(count + "," + rnd.Next(1, 100));
                }
                count = 0;
                for (var i = 0; i < 100; i++)
                {
                    count++;
                    sw.WriteLine(count + "," + rnd.Next(1, 100));
                }
            }
        }

        
    }
}
1