0

I have 3 strings, these are not real data just an example:

string items = "Item 1, Item 2, Item 3";

string price = "300, 400, 500";

string tax = "30, 50, 60";

What I am trying to do is create an array like so:

[Item 1] => Array([Price] => 300, [Tax] => 30), [Item 2] => Array([Price] => 400, [Tax] => 50), [Item 3] => Array([Price] => 500, [Tax] => 60)

the problem is I have no idea how to do this in ASP.NET, if I had to do this in PHP, this would be no problem.

4
  • Why not make a method that you can invoke? This method would take in an array or list as a parameter and then the filter. So, then in your method, you just loop through the array elements of the given array and return a filtered an array to use in your code. Commented May 7, 2015 at 2:29
  • 1
    C# arrays are not associative. It looks like you want a Dictionary (of dictionaries), or perhaps more idiomatically, a list of objects whose type is a class called Item with Name, Price and Tax properties. Commented May 7, 2015 at 2:32
  • @Blorgbeard Good catch. If the 3 array relate to each other, they shouldn't be 3 separate arrays. Dictionary would be more appropriate. Commented May 7, 2015 at 2:36
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Besides, what would this have to do with ASP.NET? Commented May 7, 2015 at 2:49

1 Answer 1

6

In C#, you would probably declare a class like:

class Item {
    public string Name { get; set; }
    public decimal Price { get; set; }
    public decimal Tax { get; set; }
}

And then you could split your strings into arrays and parse them into a list of Item:

string items = "Item 1, Item 2, Item 3";    
string price = "300, 400, 500"; 
string tax = "30, 50, 60";  

var names = items.Split(',');
var prices = price.Split(',');
var taxes = tax.Split(',');

var list = new List<Item>();

for (int i = 0; i < names.Length; i++) {
    list.Add(new Item() {
        Name = names[i].Trim(),
        Price = decimal.Parse(prices[i]),
        Tax = decimal.Parse(taxes[i])
    });
}

The above is pretty brittle: I'm assuming each list has the same number of elements, and there's no handling for parse failures converting the strings to decimal; but you get the idea.

Here's a fiddle that runs the above code.

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

1 Comment

if you could use the for loop wont it be cleaner? +1

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.