-3

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

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?

nightfire001
  • 759
  • 3
  • 20
  • 50

4 Answers4

7

I suggest you to create some class to hold this data:

public class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Address { get; set; }
   public string Contact { get; set; }
}

Then read people from your file:

var person = File.ReadLines("file.csv").Skip(1)
                 .Select(ParsePersonFromLine)
                 .Where(p => p.Name == "Peter")
                 .FirstOrDefault();

if (person != null)
   // use person.Address

Parsing of person can look like:

private static Person ParsePersonFromLine(string line)
{
    string[] parts = line.Split(',');
    return new Person {
        Id = Int32.Parse(parts[0]),
        Name = parts[1],
        Address = parts[2],
        Contact = parts[3]
    };
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3

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");

EDIT:

        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];
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
  • 1
    it will be better if youuse ReadLines instead :) – BRAHIM Kamel Feb 04 '14 at 16:18
  • You should really indent your code. – Servy Feb 04 '14 at 16:20
  • @K.B: Yes i agree with you , performance wise it is much better than `ReadAllLines()`. – Sudhakar Tillapudi Feb 04 '14 at 16:23
  • `ReadLines` doesn't return a `string[]`, but your code assumes that it does. – Servy Feb 04 '14 at 16:23
  • @Servy: Thanks for your valuable point,Sorry its my mistake. – Sudhakar Tillapudi Feb 04 '14 at 16:26
  • @Servy that's true it returns IEnumerable – BRAHIM Kamel Feb 04 '14 at 16:26
  • 1) This answer doesn't support quote escaped commas within the file. 2) The name check seems like it should be for equality, not `Contains`. 3) Placing this inside of a method implies that it should be used multiple times to search for different names. This is horribly inefficient. If that is the goal, the file should be parsed into a data structure that can be efficiently searched. 4) It doesn't consider the case of multiple matches in the file; it's unclear if that is needed or not. – Servy Feb 04 '14 at 16:33
  • 1) instance fields cannot be implicitly typed variables. 2) There's no point in pulling `strLines` out to an instance field anyway. It's not helping in the least. It might as well just be a local variable. – Servy Feb 04 '14 at 16:43
  • @Servy: Thanks for your valuable points , could you please give me some idea on your 3rd point 3)If that is the goal, the file should be parsed into a data structure that can be efficiently searched. – Sudhakar Tillapudi Feb 04 '14 at 16:53
  • Honestly, it would astound me that you couldn't figure out on your own what an appropriate data structure for efficiently finding an address, given a name, would be, or that you wouldn't comprehend the drawbacks of searching through a file and parsing it repeatedly to find the value for a key. Those are things I'd expect a first year CS student to understand. – Servy Feb 04 '14 at 16:55
  • @Servy: i'm thinking that `Dictionary` would help the OP as he has name as `Key` and Address as `Value`.any comments? – Sudhakar Tillapudi Feb 04 '14 at 17:09
  • @SudhakarTillapudi Yes, if he needs to search the data repeatedly, that is probably the correct data structure to use. – Servy Feb 04 '14 at 17:15
  • @Servy: my edited post contains usage of `Dictionary` , could you please have a Look? – Sudhakar Tillapudi Feb 04 '14 at 17:28
  • That's addressed some of the points, but not all of them. It also lacks any explanation at all as to what's going on. – Servy Feb 04 '14 at 17:34
1

If your file is well-formatted this should work.

var values = File.ReadLines("file.csv")
                 .Skip(1)
                 .Select(line => line.Split(','))
                 .ToList();

var address = values.Where(x => x[1] == "Peter")
                    .Select(x => x[2])
                    .First();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • This will fail to read *well formatted* CSV files that contain quote escaped commas within it. – Servy Feb 04 '14 at 16:18
0

try this

class Program
    {
        static void Main(string[] args)
        {
            List<string> resLines = new List<string>();
            var lines  = File.ReadLines("file.csv");
            foreach (var line in lines)
            {

                //here I suppose that your csv file it like this 
                    // 1,Peter,USA,12345
                    // 2,Anna,UK,45678
                var res = line.Split(new char[] {','});
              //or name to search 
                if (res[1] == "Peter")
                {                        
                    resLines.Add(res[2]);

                }
            }
            //to get the output  
            foreach (var line in resLines)
            {
                Console.WriteLine(line);
            }

        }
    }
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
  • This will yield lines that have the text of the given name in some other field besides the one that is in question. – Servy Feb 04 '14 at 16:19
  • ok but let's suppose you search peter but peter exists in UK and USA ? I'm just showing how he can do it for a later use – BRAHIM Kamel Feb 04 '14 at 16:20
  • What about it? I don't have a problem with the fact that you have multiple lines in the result, I have a problem with the fact that you're searching the entire line for the name, not just the name column. – Servy Feb 04 '14 at 16:21