开发者

c# how do i return a generic list?

开发者 https://www.devze.com 2023-01-24 21:41 出处:网络
List<decimal> FindSumSubset(decimal sum, List<decimal> list) { for (int i = 0; i < list.Count; i++)
List<decimal> FindSumSubset(decimal sum, List<decimal> list)
        {
           for (int i = 0; i < list.Count; i++)
           {
              decimal value = list[i];
              if (sum - value == 0.0m)
              {
                  return new List<decimal> { value };
              }
              else
              {
                  var subset = FindSumSubset(sum - value, list.GetRange(i + 1, list.Count -i));
                  if (subset != null)
        开发者_Go百科          {
                      return subset.Add(value);


                  }
              }
           }
           return null;
        }

i am getting an error on this line:

 return subset.Add(value);

the error:

Error   1   Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<decimal>'

anyone know how i can fix this>?


subset.Add(value);
return subset;

Your problem has nothing to do with generic lists. The Add method only changes the list, but does return void/doesn't return anything. So you'll need to make the return a separate statement and can't chain method calls.


subset.Add doesn't return the list object that you're adding elements to. It returns void as it just does the work.

Do:

subset.Add(value);
return subset;


 if (subset != null)
                  {
                      subset.Add(value)
                      return subset;


                  }
0

精彩评论

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