Reputation: 2901
I have an IEnumerable and I want to use a linq statement to serialize each object in the IEnumerable and return another list. Here's my foreach I have:
List<EventData> payloads = new List<EventData>();
foreach (var request in requestList)
{
string message = JsonConvert.SerializeObject(request);
EventData data = new EventData(Encoding.UTF8.GetBytes(message));
payloads.Add(data);
}
I was attempting to do a Select statement like this:
requestList.Select(request => { JsonConvert.SerializeObject(request); });
Error message is :
The type arguments for method 'Enumerable.Select<TSource, TResult>(IEnumerable, Func<TSource, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly
Upvotes: 0
Views: 94
Reputation: 37080
The problem with the original code was that there is a method body defined with curly braces, but it doesn't return anything. To fix this, you can simply take your existing code and put it into the select statement, but add a return
statement from the block:
List<EventData> payloads = requestList.Select(request =>
{
string message = JsonConvert.SerializeObject(request);
EventData data = new EventData(Encoding.UTF8.GetBytes(message));
return data;
}).ToList();
Or you could do the same thing without the method body approach, but this sometimes makes the code a little harder to read and debug, since you're doing everything in one line:
List<EventData> payloads = requestList
.Select(request =>
new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request))))
.ToList();
Upvotes: 1