hi experts i have a csv file which look like this

country,date,code,time
mexico,3/13/2008,92,00:00:00
mexico2,3/13/2008,5214,00:00:00
mexico2,3/13/2008,5214,00:00:00

i am reading the file like this

StreamReader sr = new StreamReader(@"C:\Documents and Settings\jitendra\Desktop\RIC_SELL_080318.csv");

string strline="";
string[]value=null;
while(!sr.EndOfStream)
{
   strline=sr.ReadLine();
  value=strline.Split(',');
if(values.Lenght >3 )
{
   Console.WriteLine(values[2].ToString());
}
}

so on doing this i get the code coloumn data but it is not giving the complete records from the file , and what i want is to read this file using array and only want to get the data of code coloumn and sort it in descending order. so can you plz help me plz its urgent thanking you in advance....

Dani AI

Generated

a few things are tripping you up:

  • You are sorting and writing while you are still reading. Do the sort and write after you have read all rows.
  • Split(',') will miscount fields when a value is quoted and contains commas or newlines, so your length check drops many records.
  • If you want a numeric sort, parse the code column to int; reversing strings will not give the right order.
  • Always dispose your reader/writer to flush everything.

Here is a compact, safe way to read the CSV, grab the 3rd column (code), sort descending numerically, and write it out. It handles quoted fields and embedded commas/newlines.

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualBasic.FileIO;

var codes = new List<int>();

using (var parser = new TextFieldParser(@"C:\Documents and Settings\jitendra\Desktop\RIC_SELL_080318.csv"))
{
    parser.SetDelimiters(",");
    parser.HasFieldsEnclosedInQuotes = true;
    parser.TrimWhiteSpace = true;

    // skip header
    if (!parser.EndOfData) parser.ReadFields();

    while (!parser.EndOfData)
    {
        var f = parser.ReadFields();
        if (f?.Length >= 3 && int.TryParse(f[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var code))
            codes.Add(code);
    }
}

var sorted = codes.OrderByDescending(c => c).Select(c => c.ToString(CultureInfo.InvariantCulture));
File.WriteAllLines(@"C:\list.txt", sorted);

is right that a List<string> helps, but prefer OrderByDescending on the parsed ints rather than Reverse, which only inverts the current order.

for your data, split each line, pick the token that parses as an int for age, and write back as name,age,place. Quick idea: find ageToken = parts.First(p => int.TryParse(p, out _)), then use the remaining two tokens as name/place in the order you need. Add validation if names can contain digits.

Recommended Answers

All 4 Replies

Add the values in List<String> and use some List methods like Reverse,....

hey Rammy i have tried list and my code worked i am experiencing a problem with stream writer it is not reading the whole records of the file my original file contains 361 recors including header but the code which i have written using streamReader.ReadLine() method does not reads the whole file it skips the last 83 records it is only giving me 278 records. On using streareader.ReadToEnd gives me the whole records but then it does not gives the value of array. so where i am making mistake i am not getting see i am sending my code have a look at it and please help me....

StreamReader sr= new StreamReader(@"C:\Documents and Settings\jitendra\Desktop\RIC_SELL_080318.csv");
            StreamWriter sw = new StreamWriter(@"C:\list.txt");

            string strline = "";
            string[] values = null;
            IList<string> list = new List<string>();
IList<string> list = new List<string>();
 while (!sr.EndOfStream)
{
strline = sr.ReadLine();
values = strline.Split(',');
if (values.Length > 3)
{
                    list.Add(values[2].ToString());
}
IComparer myComparer = new myReverserClass();  
            string[] final = new string[list.Count]; 
            list.CopyTo(final,0); 
            Array.Sort(final, myComparer); 
            foreach (string var in final)
            {
                sw.WriteLine(var);
            }
public class myReverserClass : IComparer 
             {
                // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
                int IComparer.Compare(Object x, Object y)
               {
                return ((new CaseInsensitiveComparer()).Compare(y, x));
               }
            }

Send me the text file @ and I'll try myself

Mithun,23,Blore
23,Santhosh,Blore
Deepak,24,Chinthmani
NARESH,Chinthmani,23
Rao,26,Andhra
Blore,24,Abhi


My data is in this form i need to arrange it as name,age ,place and it should be stored
please send the code in C# send to

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.