开发者

How to convert this recursive code to Linq

开发者 https://www.devze.com 2023-01-05 00:17 出处:网络
Can anyone tell me how to best possible way to convert the followi开发者_如何学编程ng code to LINQ:

Can anyone tell me how to best possible way to convert the followi开发者_如何学编程ng code to LINQ:

static int MyMethod(MyClass my, bool b)
{
  int cnt = 0;

  foreach(SomeClass cls in my.SomeMethod()
  {
    cnt = cnt + cls.length;
  }

  if(b == true)
  {
    foreach(MyClass aa in my.SomeOtherMethod())
    {
      cnt = cnt + MyMethod(aa, true); // recursive
    }
  }

  return cnt;
}

Please see that I know that the code above works fine, but I need to write it in LINQ and compare.


As Darin says, you can't easily recurse without doing so explicitly - but you can still simplify this code with LINQ:

static int MyMethod(MyClass my, bool b)
{
  int cnt = my.SomeMethod().Sum(cls => cls.length);    
  if (b)
  {
      cnt += my.SomeOtherMethod().Sum(aa => MyMethod(aa, true));
  }    
  return cnt;
}


First of all, you should use the solution by Jon, because it is the most straightforward and readable soltion you can get. However, you can write recursive Func<...> declarations in C#, so the code could be rewritten like this:

Func<MyClass, bool, int> myFoo = null;
f = (my, b) =>
    my.SomeMethod().Sum(cls => cls.length) +
    (b ? my.SomeOhterMethod().Sum(aa => myFoo(aa, true)) : 0);

This is essentially the same thing as what Jon posted, with the exception that I'm using Func<..> instead of a full method. (This can be useful for encoding recursion in LINQ queries, but I think it is useful only very rarely)


You cannot write recursive queries with LINQ.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号