I was writing a function to parse an input from a string to get all the integers into a list. However, I got an an error:
The type arguments for method
System.Linq.Enumerable.SelectMany<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,System.Collections.Generic.IEnumerable<TResult>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Now I have tried to specify them but to not avail.
The logic of the code (using example input of "56#3=45#90") is:
So I am splitting "56#3=45#90" (on '=')
into a string array of {"56#3", "45#90"}
to be operated on by Select, which will split (on '#')
into Enumerable( IEnumerable(string)
) containing "{"56", "3"},{"45", "90"}
. Finally, the SelectMany
is supposed to flatten the structure (and convert to int) into {56, 3, 45, 90}
which should be able to be converted into a list.
I don't see any reason why there's something wrong with specifying type arguments.
// string 'a' contains "<int>#<int>=<int>#<int>" such as "56#3=45#90";
public static IList<int> ParseCKPInput(string a)
{
return (a.Split('=')).Select(n => n.Split('#')).SelectMany(n => Convert.ToInt32(n)).ToList();
}
I understand this can be done by regex (which I have implemented now); however, I want to improve my understanding of LINQ and figure out what is wrong with my original code. Thanks everyone!
The reason why .SelectMany(n => Convert.ToInt32(n))
doesn't work is because n
will be a list, and you can't convert a list to an int.
The query should be :
return a.Split('=')
.Select(n => n.Split('#'))
.SelectMany(x => x)
.Select(x => Convert.ToInt32(x))
.ToList();
Or... there is no need to flatten this just pass all the split characters in at once:
return a.Split('=', '#')
.Select(x => Convert.ToInt32(x))
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.