Reputation: 433
I need a data structure in C# that can hold 2 things:-
After that i need to iterate over a list of such structure.
Is creating a class like below the only option?
public class ResourceFile
{
public string FilePath { get; set; }
public string Language { get; set; }
}
And then creating a list as following:
var list = new List<ResourceFile>()
I don't want to create an additional class file in project for this minor requirement.
Other options that I considered but not sure if they are right:-
List<Dictionary<string, string>>
But the key and value are not related in typical key value pair relationship.
In this case, Path can't be a key to language.
List<Tuple<string, string>>
This is probably the closest to fulfilling my requirement.
However since i have never used Tuples before, not sure if my use case is valid for using Tuples.
So here i can have a list of Tuples.
Each tuple will hold 2 values. First value will be path and second one will be language.
Any other options?
Upvotes: 0
Views: 1148
Reputation: 46
With c# > 7.0 you can use tuples syntax like this:
var files = new List<(string FilePath, string FileLanguage)>();
files.Add((FilePath: "path", FileLanguage: "lang"));
Console.WriteLine($"File 0 - PATH: {files[0].FilePath}, LANG: {files[0].FileLanguage}");
It acts like a ValueTuples but here you can have more than only two elements and each element can be named.
More info here: https://learn.microsoft.com/dotnet/csharp/tuples
Upvotes: 3
Reputation: 133
Your list of tuples idea is a good option if you don't want to create a new class. Tuples are data structures that simply help group information without forcing the key, value structure as you mentioned.
The one thing you should keep in mind when using tuples is that they are immutable - meaning you can't add, remove, swap, etc. elements inside the tuple once assigned. A List however is mutable, so you could add or remove tuples from the list.
Upvotes: 1