使用C#在CSV文件中搜索值 [英] Search value in csv file using c#

查看:701
本文介绍了使用C#在CSV文件中搜索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 file.csv 的csv文件,其中包含以下数据

I have a csv file named file.csv which contains data as follow

Id   Name     Address   Contact
 1   Peter    USA       12345
 2   Anna     UK        45678
 3   John     USA       9876

我想使用c#搜索名称,然后从地址返回值. 例如.如果用户是Peter的searc,则应该返回美国.

I want to search for the Name using c# and return the value from the Address. For eg. If the user searc for Peter then, USA should be returned.

任何人都可以给我一些想法吗?

Can anyone give me some idea?

推荐答案

您可以创建一个函数来执行以下任务:

You can create a function to do this task as below:

String GetAddress(String searchName)
{       
   var strLines=File.ReadLines("filepath.csv");
   foreach(var line in strLines)
   {
      if(line.Split(',')[1].Equals(searchName))
         return line.Split(',')[2];
   }

   return "";
}

您可以按以下方式调用上述函数:

you can call the above function as below:

String peterAddress=GetAddress("Peter");

        String address="";
        Dictionary<String, String> dict_Name_Address = new Dictionary<string, string>();
        var lines=File.ReadLines("FileName.csv");
        foreach (var line in lines)
        {
            dict_Name_Address.Add(line.Split(',')[1],line.Split(',')[2]);
        }
        if(dict_Name_Address.ContainsKey(searchKey))
         address = dict_Name_Address[searchKey];

这篇关于使用C#在CSV文件中搜索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆