简体   繁体   中英

Naming of parse string and assign value

Sometimes I have this kind of code, Any advise to improve the readability of result[0], result[1]...event the naming of result

var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new 
{ 
Name = result[0], 
BuyPrice = result[1], 
SellPrice = result[2], 
};

I don't how you get productData but is it possible to maybe get it as a json? That would improve the readability alot instead of splitting it and get string based on positions.

That's probably overkill, but you could use an extension method based on C# 7 and ValueTuple to name your values right away. For instance:

public static class StringExtensions
{
    public static ValueTuple<string, string, string> Split(this string input, string delimiter)
    {
        var values = input.Split(new[] { delimiter }, StringSplitOptions.None);

        return (values[0], values[1], values[2]);
    }
}

Then use it like that:

var (name, buyPrice, sellPrice) = productData.Split(" ");

Console.WriteLine(name);

Edit: Actually, there's a smarter way. Just write an extension method to deconstruct an array:

public static class ArrayExtensions
{
    public static void Deconstruct<T>(this T[] values, out T item1, out T item2, out T item3)
    {
        item1 = values[0];
        item2 = values[1];
        item3 = values[2];
    }
}

Now you can just use the original string.Split and assign the values like the first example:

var (name, buyPrice, sellPrice) = productData.Split(new[] { " " }, StringSplitOptions.None);

Create Extension Method On The String Class Which Will Do The Split and Return an Object Of ProductData Class

public static YourProductClass GetProductFromString(this string CompinedString)
{
   // Do You Splitting Stuff Here and Assign The Values From String To NewProduct
   return NewProduct;
}

Then In You Code

var ProductData  = "Egg 1.24 1.36".GetProductFromString();

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