简体   繁体   中英

c# how do i return a generic list?

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


                  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM