0
votes

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

1
I get an error saying: The type arguments for method 'Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitlyDannyD
var list = requestList.Select(request => new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request)))).ToList();15ee8f99-57ff-4f92-890c-b56153
The problem is that the curly brackets mean you have a method body, but you're not returning anything from it.juharr
What type is requestList?John Wu
Side note: typically variables of a collection type are named with the plural of the type they contain, so if requestList is a List<Request>, it would simply be named requests.Rufus L

1 Answers

1
votes

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();