简体   繁体   中英

Get first and last column value in C#

I am using the following code in my .NET web service that gets its data form a CSV file.

private List<Item> ietms = new List<Item>();

public ItemRepository()
{
    string filename = HttpRuntime.AppDomainAppPath + "App_Data\\items.csv";

    var lines = File.ReadAllLines(filename).Skip(1).ToList();

    for (int i = 0; i < lines.Count; i++)
    {
        var line = lines[i];

        var columns = line.Split('$');

        //get rid of newline characters in the middle of data lines
        while (columns.Length < 9)
        {
            i += 1;
            line = line.Replace("\n", " ") + lines[i];
            columns = line.Split('$');
        }

        //Remove Starting and Trailing open quotes from fields
        columns = columns.Select(c => { if (string.IsNullOrEmpty(c) == false) { return c.Substring(1, c.Length - 2); } return string.Empty; }).ToArray();

        var temp = columns[5].Split('|', '>');

        items.Add(new Item()
        {
            Id = int.Parse(columns[0]),
            Name = columns[1],
            Description = columns[2], 
            Category = temp[0]
        });
    }
}

This code gets a list of products from the CSV file along with its name, description etc. Each product belongs to either one or two categories : Category = temp[0] .

Each product's category is found in a column of the csv file with it's data structured as such:

Groups>Subgroup>item , in which case, this product belongs to category "Groups".

The category column of a product may also be structured as:

MajorGroup|Groups>Subgroup>item , in which case this product belongs to category "MajorGroup".

Also, in many cases a product's category column may be structured as:

MajorGroup|Groups>Subgroup>item|SecondGroup , in which case this product belong to both the categories "MajorGroup" and "SecondGroup"

The code above that I am currently using does half the job. If a product has a category defined in the CSV file as MajorGroup|Groups>Subgroup>item|SecondGroup , it assigns it to category "MajorGroups" but not "SecondGroup".

This line var temp = columns[5].Split('|', '>'); gets the first value structured taht way and separated by a pipe and sets it as the product's category here Category = temp[0] .

How do I fix this so that if the category is structured as MajorGroup|Groups>Subgroup>item|SecondGroup , with two categories, then it will show up in both categories.

How do I assign the product to one or more categories depending on the structure of the category column data.

This works for the most part, but how do I alter the code to check and assign for both categories?

Can I change this var temp = columns[5].Split('|', '>'); to get both teh first and the last value if it exists and assign both to Category = temp[0] .

You should definitely use some CSV parser instead of doing this manually. There are too many potential problems and issues when parsing CSV manually that it is much easier and faster to use some existing tool like:

To get the second group values given the problem statement as specified you could do the following.

    ...
    var temp = columns[5].Split('|', '>');
    string categories= temp[0];
    if (input.Count(x => x == '|') >= 2)
    {
        categories+= "," + temp.Last();
    }
    ...
    Category = categories;

Then one could get a list of Items that is assigned to a category by the following function:

    static public IList<Item> GetProductsByCategory(string category, IList<Item> items)
    {
        return items.Where(x => x.Category.Split(',').Contains(category,StringComparer.OrdinalIgnoreCase)).ToList();
    }

A much cleaner solution is to store the categories within the Item class as something that implements ILIST .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM