0

I do a project in c# winforms.

I want to get first column value in csv.

var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
 var line = reader.ReadLine();
 var values = line.Split(';');
 listA.Add(values[0]);

}


------------------
no    |name     | 

------------------
1     |wwwwww
2     |yyyyy
3     |aaaaa 
4     |bbbbbb

Now I am using above this code. It gives the value row by row. i want all name value in listA

Any one have idea?

11
  • You are already getting the first column so what is the question? Commented Jul 26, 2013 at 10:58
  • Your requirements are not clear. Can you show an example of input data, and an example of the data you want to get out Commented Jul 26, 2013 at 10:58
  • now the output is first row.I want first column @TimSchmelter Commented Jul 26, 2013 at 10:59
  • isn't your col separator a comma? You seem to be splitting on ';' which is more likely your row separator. That would explain it ... Commented Jul 26, 2013 at 11:00
  • Your list contains the first column of all rows, so it's not clear what's wrong with it. Since you don't show how you output it, maybe the reason for your issue is there. Commented Jul 26, 2013 at 11:00

4 Answers 4

1

There is now way to read column in CSV without reading whole file. You can use some wrappers (for example: LINQ to CSV library) but they will just "hide" reading operation.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes - you're currently spliting on ;

Try using a comma instead.

Better to use a dedicated library btw...

Comments

1

Some frown upon Regex but I think it provides good flexibility. Here is an example inspired by Adrian Mejia. Basically, you can choose particular characters between which the delimiter is valid in the context. i.e. a comma in "hello, world" or 'hello, world' would be valid.

    static void Main(string[] args)
    {
        string csv = "Hello,1,3.5,25,\"speech marks\",'inverted commas'\r\nWorld,2,4,60,\"again, more speech marks\",'something else in inverted commas, with a comma'";

        // General way to create grouping constructs which are valid 'text' fields
        string p = "{0}([^{0}]*){0}"; // match group '([^']*)' (inverted commas) or \"([^\"]*)\" (speech marks)
        string c = "(?<={0}|^)([^{0}]*)(?:{0}|$)"; // commas or other delimiter group (?<=,|^)([^,]*)(?:,|$)
        char delimiter = ','; // this can be whatever delimiter you like
        string p1 = String.Format(p, "\""); // speechmarks group (0)
        string p2 = String.Format(p, "'"); // inverted comma group (1)
        string c1 = String.Format(c, delimiter); // delimiter group (2)
        /*
         * The first capture group will be speech marks ie. "some text, "
         * The second capture group will be inverted commas ie. 'this text'
         * The third is everything else seperated by commas i.e. this,and,this will be [this][and][this]
         * You can extend this to customise delimiters that represent text where a comma between is a valid entry eg. "this text, complete with a pause, is perfectly valid"
         * 
         * */
        //string pattern = "\"([^\"]*)\"|'([^']*)'|(?<=,|^)([^,]*)(?:,|$)";
        string pattern = String.Format("{0}|{1}|{2}", new object[] { p1, p2, c1 }); // The actual pattern to match based on groups

        string text = csv;

        // If you're reading from a text file then this will do the trick.  Uses the ReadToEnd() to put the whole file to a string.
        //using (TextReader tr = new StreamReader("PATH TO MY CSV FILE", Encoding.ASCII))
        //{
        //    text = tr.ReadToEnd(); // just read the whole stream
        //}

        string[] lines = text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); // if you have a blank line just remove it?
        Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); // compile for speed

        List<object> rowsOfColumns = new List<object>();
        foreach (string row in lines)
        {
            List<string> columns = new List<string>();
            // Find matches.
            MatchCollection matches = regex.Matches(row);
            foreach (Match match in matches)
            {
                for (int ii = 0; ii < match.Groups.Count; ii++)
                {
                    if (match.Groups[ii].Success) // ignore things that don't match
                    {
                        columns.Add(match.Groups[ii].Value.TrimEnd(new char[] { delimiter })); // strip the delimiter
                        break;
                    }
                }
            }
            // Do something with your columns here (add to List for example)
            rowsOfColumns.Add(columns);
        }
    }

1 Comment

You know, there's an old saying that if you have a problem and decide to solve it with regular expression... now you have two problems. ;-) Fun aside, I'm a fan of regex in small doses, but it can get crazy in a hurry.
0
var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
List<string> listA = new List<string>();

while (!reader.EndOfStream)
{

 var line = reader.ReadLine();

string[] dates = line.Split(',');           
for (int i = 0; i < dates.Length; i++)
  {
  if(i==0)
  listA.Add(dates[0]);
  }


 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.