Reputation: 639
I have a Gain class and a list of this class filled with data:
internal class Gain {
internal string asset { get; set; }
internal float amount { get; set; }
internal float cost { get; set; }
}
private static List<Gain> Gains = new List<Gain>();
The user can send string commands, like "AssetName" or "amount", to get specific data.
string asset="AssetName";
string datatype="amount"; // or "cost" etc
In C#, is there a compact syntax to select the specific data for a specific asset in the Gains list in just one line, like:
return Gains[AssetName].[datatype]; // or something like this
Upvotes: 0
Views: 79
Reputation: 814
In addition to original @Guru Stron's answer, if you need rich dynamic filtering too, below code helps you.
internal static T Get<T>(Func<Gain, bool> criteria, Func<Gain, T> selector)
{
return Gains.Where(criteria).Select(selector).First();
}
Usage :
Get(x => x.asset == "assetName", x => x.amount);
Get(x => x.asset == "assetName2" && x.amount > 10, x => x.cost);
Upvotes: 3
Reputation: 141980
In short - no. It does not fully answer your question, but you can use LINQ:
Gains
.Where(g => g.asset == asset)
.Select(g => g.amount)
.FirstOrDefault() // or First, or Single or SingleOrDefault
If you want the selection to be dynamic based on some number of strings you will need to implement it yourself either via some reflection magic or creating predicate and selections functions dictionaries based on string (and you will have some problems with return types if you don't want to cast everything to object).
Also instead of strings you can leverage C# type system, generics and ability to pass functions(lambdas):
internal static T Get<T>(string assetName, Func<Gain, T> selector)
{
return Gains.Where(g => g.asset == assetName).Select(selector).First();
}
With usage:
Get(asset, g => g.amount)
Upvotes: 3
Reputation: 81
You could use the LINQ library to work with the collection. Are the asset names unique? As in, if you look up a specific assest name are you maximum only going to find one instance of the Gain class that matches this asset name?
Assuming that it is, and for example you want to get the cost of the gains object with the asset name "example", you could do:
var cost = Gains.First(x => x.asset == "example").cost;
First will throw an error if it doesn't find anything matching the conditon. Alternatively FirstOrDefault
will return a default value if it doesn't find any Gains object matching your condition. If they aren't unique and its possible to find more than one object matching your condition, you could filter the List with Where
to get all those that match the condition, and then handle that resulting List collection.
Gains.Where(x => x.asset == "example")
There are other methods too that you could use such as Single() etc that I would recommend reading about
Upvotes: 2
Reputation: 599
Something like
return Gains.Where(p => p.asset == "assetName").Select(p => p.amount).FirstOrDefault();
does not work?
Upvotes: 1