【问题标题】:Get the element with in the array whose occurrence is 4 times获取数组中出现4次的元素
【发布时间】:2017-04-23 17:39:26
【问题描述】:

我有一个字符串数组,我想在数组中找到那些出现4次或4次以上的元素。

我的代码

internal static void ProcessArray(string[] numArray)
        {
            string response = string.Empty;

            var duplicates = (numArray
                        .GroupBy(e => e)
                        .Where(e => e.Count() >= 4)
                        .Select(e => e.First())).ToList();
//do some further business logic
    }

所以 duplicate 应该返回一个包含该元素的字符串列表。

我在下面的方法中调用它

Public static string GetDuplicates()
{

 string[] s = new new string[]{" 1","1","2","2","2","1","3,"2","1" }
 string result = ProcessArray(s);
return result
}

它只返回列表中的2,正确的结果应该是列表中的1,2。

【问题讨论】:

  • 请把它放在一起作为minimal reproducible example,而不是方法的一部分和输入的一部分。
  • 您的第一个 1 有空格。使用 Trim 截断它,或者如果您只使用整数将输入解析为 int 使用 Array.ConvertAll
  • @JonSkeet 我已经更正了
  • 您尚未提供minimal reproducible example。我可以复制/粘贴/编译/运行您的代码并查看不正确的结果吗?不...

标签: c# arrays linq


【解决方案1】:
var values = new string [] { "1", "1", "2", "2", "2", "1", "3", "2", "1" };
var groups = values.GroupBy(i => i).Select(i => new { Number = i.Key, Count = i.Count() });
foreach(var item in groups)
{
 if(item.Count == 4)
 {
    Console.WriteLine(item.Number);
 }
}

WORKING FIDDLE

【讨论】:

  • 信不信由你,这不是我 ;-) 仅仅因为我发表评论并不意味着我投反对票或投赞成票 ;-)
  • @CodeNotFound 我不是说你!对不起
猜你喜欢
  • 2010-11-06
  • 2019-04-29
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多