I have created a helper function which accepts a string array as input and the index of the column as selected output.
public static List<T> GetByIndex<T>(string[] data, int index)
{
List<T> list = new List<T>();
foreach (var item in data)
{
if (item.Contains("|"))
{
string[] s = item.Split("|");
list.Add(s[index]);
}
}
return list;
}
At line list.Add(s[index]);
i get the error Cannot convert from 'string' to 'T'.
How can i make this method generic?
The function should return string or integer or even maybe boolean
CodePudding user response:
How can i make this method generic?
You shouldn't. You're only dealing with strings so make the method return a List<string>
public static List<string> GetByIndex(string[] data, int index)
{
var list = new List<string>();
foreach (var item in data)
{
if (item.Contains("|"))
{
string[] s = item.Split("|");
list.Add(s[index]);
}
}
return list;
}
If you need to also support int
then just make an overload which returns a List<int>
and use int.Parse
/ int.TryParse
.
CodePudding user response:
It seems that you don't want generic T
at all: what is the expected output for, say, T == IComparer<DateTime>
?
I suggest getting rid of T
and returning List<string>
:
public static List<string> GetByIndex(string[] data, int index) {
// Public method's arguments validation
if (data is null)
throw new ArgumentNullException(nameof(data));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
List<string> list = new List<string>();
foreach (string item in data) {
// Do not forget about nulls
if (item != null) {
// We can stop earlier on Split:
// if, say, index == 2 we don't want all 12345 items
string[] s = item.Split('|', index 2);
// s can well be too short
if (s.Length > index)
list.Add(s[index]);
}
}
return list;
}
CodePudding user response:
If you want to return a List<T>
, you need to provide some way of converting each string into a T
.
Such as:
public static List<T> GetByIndex<T>(
string[] data,
int index,
Func<string, T> convertItem)
{
List<T> list = new List<T>();
foreach (var item in data)
{
if (item.Contains("|"))
{
string[] s = item.Split("|");
list.Add(convertItem(s[index]));
}
}
return list;
}
And you could provide convenience overloads for the types you commonly use.
For example:
public static List<int> GetIntByIndex(string[] data, int index)
{
return GetByIndex(data, index, int.Parse);
}