【问题标题】:how can I use linq to return another list如何使用 linq 返回另一个列表
【发布时间】:2019-09-11 18:16:51
【问题描述】:

我有一个 IEnumerable,我想使用 linq 语句来序列化 IEnumerable 中的每个对象并返回另一个列表。这是我的 foreach:

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

我正在尝试执行这样的 Select 语句:

requestList.Select(request => { JsonConvert.SerializeObject(request); });

错误信息是:

无法从用法中推断方法“Enumerable.Select(IEnumerable, Func)”的类型参数。尝试明确指定类型参数

【问题讨论】:

  • 我收到一条错误消息:The type arguments for method 'Enumerable.Select&lt;TSource, TResult&gt;(IEnumerable&lt;TSource&gt;, Func&lt;TSource, TResult&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly
  • var list = requestList.Select(request =&gt; new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request)))).ToList();
  • 问题是大括号意味着你有一个方法体,但你没有从中返回任何东西。
  • requestList是什么类型?
  • 旁注:通常集合类型的变量以它们所包含的类型的复数形式命名,因此如果requestListList&lt;Request&gt;,它会简单地命名为requests。跨度>

标签: c# linq


【解决方案1】:

原始代码的问题是有一个用花括号定义的方法体,但它没有返回任何内容。要解决此问题,您可以简单地将现有代码放入 select 语句中,但从块中添加 return 语句:

List<EventData> payloads = requestList.Select(request => 
{ 
    string message = JsonConvert.SerializeObject(request);
    EventData data = new EventData(Encoding.UTF8.GetBytes(message));
    return data;
}).ToList();

或者您可以不使用方法体方法来做同样的事情,但这有时会使代码更难阅读和调试,因为您在一行中完成所有操作:

List<EventData> payloads = requestList
    .Select(request => 
        new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request))))
    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多