如何在C#中找到一组多个数组中的值索引及其所属的数组

  • 本文关键字:数组 索引 一组 c# arrays
  • 更新时间 :
  • 英文 :


我有4个数组,每个数组都有与一天中的时间有关的不同值,因此:

int[] HourArray1 = {00, 04, 08, 12, 16, 20};
int[] HourArray2 = {01, 05, 09, 13, 17, 21};
int[] HourArray3 = {02, 06, 10, 14, 18, 22};
int[] HourArray4 = {03, 07, 11, 15, 19, 23};

Belo是我所能做的,以获得特定小时的索引和它所在的数组。

private void btnGetHexValue_Click(object sender, EventArgs e)
{
int HourIndex = 0;
int HourGroup = 0;
// Hours
HourIndex = Array.IndexOf(HourArray1, Convert.ToInt32(DateTime.Now.ToString("HH")));
HourGroup++;
if (HourIndex == -1)
{
HourIndex = Array.IndexOf(HourArray2, Convert.ToInt32(DateTime.Now.ToString("HH")));
HourGroup++;
if (HourIndex == -1)
{
HourIndex = Array.IndexOf(HourArray3, Convert.ToInt32(DateTime.Now.ToString("HH")));
HourGroup++;
if (HourIndex == -1)
{
HourIndex = Array.IndexOf(HourArray4, Convert.ToInt32(DateTime.Now.ToString("HH")));
HourGroup++;
}
}

我的请求:请问有没有更好、更有效的方法?

非常感谢。

您可以将数组放入另一个数组中,并使用单个LINQ查询:

int[][] allHours = { HourArray1, HourArray2, HourArray3, HourArray4 };
(int hourIndex, int hourGroup) = allHours
.Select((arr, ix) => (Position: ix + 1, FoundIndex: Array.IndexOf(arr, DateTime.Now.Hour)))
.Where(x => x.FoundIndex >= 0)
.Select(x => (x.FoundIndex, x.Position))
.DefaultIfEmpty((-1, -1))
.First();

演示:https://dotnetfiddle.net/ACDrz9

最新更新