0

I need to set 7 items from a match to 7 strings, so instead of doing something like this

var item0 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item0.ToString())).FirstOrDefault().Key;
var item1 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item1.ToString())).FirstOrDefault().Key;
var item2 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item2.ToString())).FirstOrDefault().Key;
var item3 = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.Item3.ToString())).FirstOrDefault().Key;
//...

I thought of doing something easier in a for loop like this

string[] itemsList = new string[7];
for (int j = 0; j < itemsList.Length; j++)
    {
        string nextItem = $"Item{j}";
        itemsList[j] = items.Data.Where(p => p.Key.Equals(matches[i].Participants[participantNum].stats.nextItem.ToString())).FirstOrDefault().Key; //problem is here
    }

But c# doesn't realize I'm trying to use the nextItem string. Is there a way I can use a string to define what item I want?

12
  • 2
    Dictionaries are your friend. Commented Apr 5, 2020 at 13:09
  • did you try using var nextItem = $"Item{j}"? Commented Apr 5, 2020 at 13:10
  • @Mosia What effect would that have? It will still be compiled as string nextItem = Commented Apr 5, 2020 at 13:11
  • It's also not clear where you are trying to use your nextItem within the loop because the nextItem visible on that Linq seems to be a property of another object. Commented Apr 5, 2020 at 13:12
  • 4
    Whenever you start creating variables or properties with numbers at the end like that is a good indication that you should use some type of collection instead. Commented Apr 5, 2020 at 13:30

1 Answer 1

1

You can use reflection. ie:

string[] itemsList = new string[7];
var stats = matches[i].Participants[participantNum].stats;
for (int j = 0; j < itemsList.Length; j++)
{
    var nextItem = stats.GetType().GetProperty($"item{j}").GetValue(stats).ToString();
    var v = items.Data.Where(p => p.Key.Equals(nextItem)).FirstOrDefault(); //problem is here
    itemsList[j] = (v != null)?v.Key:"";
}

PS: Probably in your model, you should define an List Items for an easier manipulation.

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

1 Comment

A list of items is a problem, I get the data with json text and can't convert it that well. But thanks for the help!

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.