How can I parse a csv file and fit it to an existing table in C#?
Okay, so right now I have a parseCSV function that returns a table to me in 2D format like so:
List<string[]> data = parseCSVFle(file);
Now, I'd like the rows in 'data' to be arranged in a particular order. This order is determined by the first column in temp (i.e. first element of the string array). The order is maintained in a string array elsewhere.
String[] dogs = {"rottweiler", "germanshepherd", "dalmatian"};
How do I rearrange 'data' to reflect the order in 'dogs'?
Additional constraints include
- The string in 'dogs' may be a substring of the string in 'data'. In this case, the string from 'dogs' is displayed.
- The string in 'dogs' may not be present in 'data' at all. In this case, the string from 'dogs' is added to the 2D table but with blanks 开发者_StackOverflowin the other columns.
Example data
data_initial
dalmatian 45 52 rottweiler 58
data_final
rottweiler 58 - germanshepherd - - dalmatian 45 52
Thanks for looking, all.
If I understand you correctly you want to sort the content of the rows by their header entry, which is one of the dogs - in that case a custom sort comparer would do the trick.
static string[] dogs = {"rottweiler", "germanshepherd", "dalmatian"};
public static int CompareRows(string[] row1, string[] row2)
{
    int idx1 = Array.IndexOf(dogs,row1[0]);
    int idx2 = Array.IndexOf(dogs,row2[0]);
    if(idx1 == idx2)
        return 0;
    else return (idx1 < idx2) ? -1 : 1;
}
public static void testArraySort()
{
    string [] data1 = { "germanshepherd", "rufus", "george"};
    string[] data2 = { "dalmatian", "mimi", "dalma" };
    string[] data3 = { "rottweiler", "fifi", "dawg" };
    List<string[]> data = new List<string[]>() { data1, data2, data3 };
    data.Sort(CompareRows);
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论