Reputation: 552
I wish to be able to modify some parameter value of generic type T, and I am trying to do this with LINQ, but I cannot figure it out.
Here is what I have:
public static T ConvertParam(T param)
{
T val = param.Select(i => { i = (T)ModifyValue(Convert.ToDouble(i)); });
return val;
}
public static UInt64 ModifyValue(double value)
{
UInt64 result = (UInt64)(value) * 3 + 1;
return result;
}
In this case the problem resides in the value returned by "ModifyValue()" that needs to be cast to whatever T param contains, but I am not sure how to do that. T can be an int, uint, int[], uint[], etc.
Handling the arrays is also tricky.
I have also tried with a normal for loop as here below:
public static T ConvertParam(T param)
{
List<UInt64> output = new List<UInt64>();
foreach (var v in param)
{
output.Add(ModifyValue(Convert.ToDouble(v));
}
return output.ToArray();
}
The problem here again is that the returned value may or may not be an array. It should just return the modified version of T param.
Note that ModifyValue() is just a dummy example. "param" MUST be generic!
Maybe I could do something around these lines (not sure how to though):
public static T ConvertParam(T param)
{
T ret = param.ToList().ConvertAll(i => i = new T() { ModifyValue(Convert.ToDouble(i)) });
return ret;
}
Upvotes: 0
Views: 121
Reputation: 306
It doesn't look to me like that would actually compile.
I think you have two vital things missing first as Pavel suggested in his comment you are returning T from ConvertParam and it takes and argument of T, but you haven't declared T.
Secondly, you are using LINQ against a generic type, but there is nothinh that allows the compiler to know that param is queryable by LINQ. I think you need to change your code to something like this
public static IEnumerable<T> ConvertParam<T>(IEnumerable<T> param)
{
// This seems redundant
// List<UInt64> output = new List<UInt64>();
var val = param.Select(i => (T)ModifyValue(Convert.ToDouble(i)));
return val;
}
public static UInt64 ModifyValue(double value)
{
UInt64 result = (UInt64)(value) * 3 + 1;
return result;
}
EDIT: As others have said I'm not sure your code makes sense from a use case point of view.
Upvotes: 1