C#不重复输出一个数组中所有元素的方法

本文介绍了一种用于数组去重并排序的算法,通过创建临时数组避免原数组被修改,然后对数组进行排序,统计不同元素数量,最终生成一个包含原数组所有不同元素的新数组。提供了函数代码实现及调用示例。

感谢原作者:https://www.xp.cn/b.php/53165.html

1.算法描述

0)输入合法性校验
1)建立临时数组:与原数组元素一样。该步骤的目的是防止传入的原数组被破坏
2)对临时数组进行排序
3)统计临时数组共有多少个不同的数字。该步骤的目的是为了确定结果集数组的长度
4)建立结果集数组,只存放不同的数字
5)返回结果集

2.函数代码

/// <summary>
/// 建立包含原数组内所有元素且元素间互不重复的新数组
/// </summary>
/// <param name="array">原数组</param>
/// <param name="isAsc">true:升序排列/false:降序排列</param>
/// <returns>新数组</returns>
private static int[] DifferentElements(int[] array, bool isAsc = true)
{
 //0.输入合法性校验
 if (array == null || array.Length == 0)
 {
  return new int[] { };
 }
 //1.临时数组:与原数组元素一样
 int[] tempArray = new int[array.Length];
 for (int i = 0; i < tempArray.Length; i++)
 {
  tempArray[i] = array[i];
 }
 //2.对临时数组进行排序
 int temp;
 for (int i = 0; i < tempArray.Length; i++)
 {
  for (int j = i; j < tempArray.Length; j++)
  {
   if (isAsc)
   {
    if (tempArray[i] > tempArray[j])
    {
     temp = tempArray[i];
     tempArray[i] = tempArray[j];
     tempArray[j] = temp;
    }
   }
   else
   {
    if (tempArray[i] < tempArray[j])
    {
     temp = tempArray[i];
     tempArray[i] = tempArray[j];
     tempArray[j] = temp;
    }
   }
  }
 }
 //3.统计临时数组共有多少个不同的数字
 int counter = 1;
 for (int i = 1; i < tempArray.Length; i++)
 {
  if (tempArray[i] != tempArray[i - 1])
  {
   counter++;
  }
 }
 //4.建立结果集数组
 int[] result = new int[counter];
 int count = 0;
 result[count] = tempArray[0];
 for (int i = 1; i < tempArray.Length; i++)
 {
  if (tempArray[i] != tempArray[i - 1])
  {
   count++;
   result[count] = tempArray[i];
  }
 }
 //5.返回结果集
 return result;
}

3.Main函数调用

static void Main(string[] args)
{
 int[] array = new int[]
 {
  1, 9, 1, 9, 7, 2, 2, 5, 3, 4,
  5, 6, 3, 3, 6, 2, 6, 7, 8, 0
 };
 //数组:包含原数组内全部元素且不重复(升序排列)
 int[] result1 = DifferentElements(array);
 foreach (int i in result1)
 {
  Console.Write(i.ToString() + "\t");
 }
 //数组:包含原数组内全部元素且不重复(降序排列)
 int[] result2 = DifferentElements(array,false);
 foreach (int i in result2)
 {
  Console.Write(i.ToString() + "\t");
 }
 Console.ReadLine();
}
<think>好的,用户之前问了关于C#数组指定列的问题,现在他们问的是如何搜索一维数组中单个元素的数量。我需要先理解用户的具体需求。 首先,“搜索一维数组中单个元素的数量”可能有两种情况:一种是统计某个特定元素数组中出现的次数,另一种是找出所有只出现一次的元素的数量。用户的问题表述太明确,需要进一步分析。 回顾用户的历史对话,之前的问题是关于数组的列操作,现在转向一维数组元素统计。可能的场景是用户在处理数据时需要统计特定元素的出现次数,或者过滤出唯一元素。比如在数据处理、分析或验证时,用户需要知道某个值出现的次数,或者找出重复项。 接下来,我需要确定用户到底需要哪一种情况。如果用户想统计特定元素的次数,那么可以使用LINQ的Count方法。如果是找出所有只出现一次的元素的数量,则需要遍历数组,统计每个元素的频率,然后计算出现次数为1的元素数量。 考虑到用户的问题中的“单个元素”,可能指的是唯一的元素,即出现一次的元素。因此,我需要提供两种情况的解决方案,并解释清楚,避免用户混淆。 另外,用户可能对性能有要求,特别是处理大数据量时。LINQ方法简洁但可能效率稍低,手动遍历更高效。需要给出两种方法,并比较它们的优缺点,让用户根据实际情况选择。 还需要注意代码示例的清晰度,确保用户能够理解并直接应用。比如,使用Dictionary来统计频率,或者使用LINQ的GroupBy。同时,提醒用户处理null值的情况,特别是在使用引用类型数组时。 最后,总结关键点,强调根据需求选择合适的方法,并提到可能的扩展方法,方便用户重用代码。确保回答全面,覆盖同可能性,并预防常见错误,如索引越界或空引用。</think>在 C# 中,若要搜索一维数组中 **某个特定元素的数量**(即统计该元素出现的次数),可以通过以下方法实现: --- ### **1. 使用 `LINQ` 的 `Count` 方法** 最简洁的方式是通过 LINQ 直接统计目标元素的数量: ```csharp using System.Linq; int[] numbers = { 1, 2, 3, 2, 4, 2, 5 }; int target = 2; int count = numbers.Count(x => x == target); Console.WriteLine($"元素 {target} 出现的次数: {count}"); // 输出:3 ``` --- ### **2. 手动遍历数组统计** 若依赖 LINQ,可手动遍历数组计数: ```csharp int[] numbers = { 1, 2, 3, 2, 4, 2, 5 }; int target = 2; int count = 0; foreach (int num in numbers) { if (num == target) count++; } Console.WriteLine($"元素 {target} 出现的次数: {count}"); // 输出:3 ``` --- ### **3. 统计所有元素的出现次数** 若需要统计数组中 **所有元素各自的数量**(例如生成频率字典): ```csharp using System.Collections.Generic; int[] numbers = { 1, 2, 3, 2, 4, 2, 5 }; var frequency = new Dictionary<int, int>(); foreach (int num in numbers) { if (frequency.ContainsKey(num)) frequency[num]++; else frequency[num] = 1; } // 输出每个元素的出现次数 foreach (var pair in frequency) { Console.WriteLine($"元素 {pair.Key} 出现次数: {pair.Value}"); } ``` --- ### **4. 查找只出现一次的元素数量** 若需统计数组中 **仅出现一次的元素的总数**: ```csharp using System.Linq; int[] numbers = { 1, 2, 3, 2, 4, 2, 5 }; // 方法1:LINQ GroupBy var uniqueCount = numbers .GroupBy(x => x) .Count(g => g.Count() == 1); // 方法2:手动统计 var frequency = new Dictionary<int, int>(); foreach (int num in numbers) { if (frequency.ContainsKey(num)) frequency[num]++; else frequency[num] = 1; } int uniqueCountManual = frequency.Count(pair => pair.Value == 1); Console.WriteLine($"唯一元素的数量: {uniqueCount}"); // 输出:3(1,3,4,5 中 1、3、4、5 出现次数为1?实际需要核对数组) // 注意示例数组实际唯一元素应为1,3,4,5,因此输出应为4 ``` --- ### **关键注意事项** 1. **性能**: - 若数组较大,直接遍历的效率优于多次 LINQ 操作。 - 使用 `Dictionary` 统计频率的时间复杂度为 O(n),空间复杂度为 O(n)。 2. **空值处理**: - 若数组包含 `null`(如 `string[]`),需在条件中显式处理 `null`: ```csharp string[] strings = { "a", null, "b", "a" }; int nullCount = strings.Count(x => x == null); // 统计 null 的数量 ``` 3. **扩展性**: - 可封装为通用方法,支持任意类型的数组: ```csharp public static int CountOccurrences<T>(T[] array, T target) { return array.Count(x => EqualityComparer<T>.Default.Equals(x, target)); } ``` --- 根据需求选择合适的方法:简单统计用 `LINQ`,高性能场景用遍历或 `Dictionary`,复杂分析可结合哈希表或自定义结构。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值