0

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

5
  • 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 explicitly Commented Sep 11, 2019 at 18:19
  • 3
    var list = requestList.Select(request => new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request)))).ToList(); Commented Sep 11, 2019 at 18:20
  • 4
    The problem is that the curly brackets mean you have a method body, but you're not returning anything from it. Commented Sep 11, 2019 at 18:22
  • What type is requestList? Commented Sep 11, 2019 at 19:20
  • 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. Commented Sep 11, 2019 at 19:49

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.