【问题标题】:Conversion c# lambda expression [duplicate]转换c#lambda表达式[重复]
【发布时间】:2019-01-16 20:22:13
【问题描述】:

如何将此请求 res 转换为 res2? 我想从一个查询中浏览对象两次。

var res = (from t1 in lst
           from t2 in lst
           select new { t1, t2 }).ToList();

var res2 = lst.Select(t1=> x)
           lst.Select(t2x=> x)
           .......

我想在res2请求中得到与res1请求相同的结果,但是使用.Select(函数。我不知道res2怎么写

链接到“选择”功能:https://docs.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.select?view=netframework-4.7.2

var query =
    fruits.Select((fruit, index) =>
                  new { index, str = fruit.Substring(0, index) });

我想对请求“res2”使用与 microsoft 示例相同的书写方式,但包含列表“lst”的 2 倍。

如何做2次以上,例如3、4、...谢谢

var res2 = lst.SelectMany(x => lst, (t1, t2) => new { t1, t2 }).ToList();

var res = (from t1 in lst
           from t2 in lst
           from t3 in lst
           from t4 in lst
           select new { t1, t2, t3, t4 }).ToList();

【问题讨论】:

  • 这段代码 (from t1 in lst from t2 in lst select new { t1, t2 }) 不会对自己进行 lst 的交叉连接(即,如果列表中有 10 个成员,您将在输出中创建 100 个新项目列表)。这就是你想要的吗?
  • 请包括样本数据和预期输出。
  • 我想将 lst 的每个对象 t1 与 lst 的每个对象 t2 进行比较。然后得到一个与我的 Where 查询对应的对象列表 t1。
  • 感谢大家的速度和答案。:)

标签: c# linq select where


【解决方案1】:

交叉连接 LINQ

var res2 = lst.SelectMany(x => lst, (t1, t2) => new { t1, t2 });

【讨论】:

  • 怎么做2次以上,比如3、4、...谢谢? t3, t4, ...
  • @Axel 这是交叉连接或称为笛卡尔连接。
  • 我找到了stackoverflow.com/questions/42930508/…var res3 = lst.SelectMany( t1 => lst.SelectMany( t2 => lst.Select( t3 => new { t1, t2, t3 })) ).ToList();
  • 感谢大家的速度和答案。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多