【问题标题】:List value return in C#C#中的列表值返回
【发布时间】:2018-08-22 16:31:38
【问题描述】:

您好,我已经比较了两个列表值,如果一个列表值大于另一个列表值,我将该值增加 +1。与其他类似。

最后再次将那 2 个列表值添加到一个列表值并想要返回但得到错误就像这些

solution.cs(42,17): 错误 CS1502: 最佳重载方法匹配 System.Collections.Generic.List<int>.Add(int)' has some invalid arguments /usr/lib/mono/4.6-api/mscorlib.dll (Location of the symbol related to previous error) solution.cs(42,21): error CS1503: Argument #1' 无法转换 System.Collections.Generic.List<int>' expression to typeint' solution.cs(43,19): 错误 CS1502: 最佳重载 System.Collections.Generic.List<int>.Add(int)' has some invalid arguments /usr/lib/mono/4.6-api/mscorlib.dll (Location of the symbol related to previous error) solution.cs(43,23): error CS1503: Argument#1' 的方法匹配无法转换 System.Collections.Generic.List&lt;int&gt;' expression to typeint' 编译失败:4 个错误,0 个警告

这是我的代码

int sum_a = 0, sum_b = 0;
for (int i = 0; i < a.Count; i++)
{
    if (a[i] > b[i])
    {
        sum_a++;
    }
    else if (a[i] < b[i])
    {
        sum_b++;
    }
}

List<int> ab = new List<int>();
ab.Add(sum_a);
List<int> ba = new List<int>();
ba.Add(sum_b);

List<int> List = new List<int>();

List.Add(ab);
List.Add(ba);
return List;
//return new List<int>> { sum_a, sum_b };

请帮助我如何在 C# 中返回这些列表

【问题讨论】:

  • 你想做什么?目前,您正尝试将两个 List&lt;int&gt; 对象添加到(当然)需要数字的 List&lt;int&gt; 中。你在找AddRange吗?
  • 别叫list list,你自己搞糊涂了。更改此行 'List List = new List();'像'List chickens = new List();',那么你可以返回鸡,而不是类型。
  • 您无法使用Add 将列表添加到列表中。 ab 显然是 List&lt;int&gt;,而不是单个 int。您可以改用List.AddRange(ab)
  • 另外pleaseplease,缩进你的代码。你怎么能读到现在写的东西?恕我直言,编码人员应该都有关于缩进的强迫症

标签: c#


【解决方案1】:

您不能以这种方式将List 插入另一个List。为此,使用AddRange

int sum_a=0,sum_b=0;
for(int i=0; i<a.Count; i++)
{
    if(a[i]>b[i])
    {
        sum_a++;
    }
    else if(a[i]<b[i])
    {
        sum_b++; 
    }
}

List<int> ab = new List<int>();
ab.Add(sum_a);
List<int> ba = new List<int>();
ba.Add(sum_b);

List<int> List = new List<int>();
List.AddRange(ab);
List.AddRange(ba);

return List;

【讨论】:

  • 请注意,将变量命名为 List 仍然是一个非常糟糕的选择(正如 Davesoft 在他的评论中指出的那样)
【解决方案2】:

就像@ManishM 所说,您不能将列表添加到列表中。您可以在其中使用 AddRange。

或者根据你的场景,你可以使用这个:

List<int> sumList = new List<int>{ sum_a, sum_b };

【讨论】:

  • 请注意,将变量命名为 List 仍然是一个非常糟糕的选择(正如 Davesoft 在他的评论中指出的那样)
猜你喜欢
  • 2017-11-01
  • 1970-01-01
  • 2021-01-19
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多