1

выполняю задание, необходимо сделать linq запрос к двумерному массиву и найти в нем заданный элемент и его индексы. простой запрос без linq findElement(value){

        foreach (int i in mas1)
        {
            if (i == value)
            {
                Console.WriteLine(i);
            }
        }

        for (int x = 0; x < row; ++x)
        {
            for (int y = 0; y < col; ++y)
            {
                if (mas1[x, y].Equals(value))
                {
                    index1 = x;
                    index2 = y;
                    Console.WriteLine(index1 + "-" + index2);
                }
            }
        }

}

2 ответа 2

1
int[,] array = { { 6, 2 }, { 4, 3 }, { 3, 4 } };
int[] linear={1,2,-4,5,6,3,0,2,3};
int value=3;

Позиция для одномерного

var res1=linear.Select((s, i) => new {Pos=i, Val=s})
    .Where(t => t.Val == value)
    .Select(t => t.Pos)
    .ToList();

Индексы строки и столбца для двумерного

int cols=array.GetLength(1);


var query2 = array.Cast<int>().Select(
(s, i) => new {PosX=i/cols, PosY=i%cols, Val=s})
    .Where(t => t.Val == value)
    .Select(t => new {t.PosX , t.PosY})
    .ToList();

вывод на экран

foreach (var item in res1)
            {
                Console.WriteLine(" {0}", item);
            }

foreach (var item in res2)
            {
                Console.WriteLine(" {0}", item);
            }
1
        int[,] mass = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

        Console.WriteLine("Введите искомое число");
        int number = int.Parse(Console.ReadLine());



        var index = (
            from i in Enumerable.Range(0, mass.GetLength(0))
            from j in Enumerable.Range(0, mass.GetLength(1))
            where mass[i, j] == number
            select  (i, j)
            ).FirstOrDefault();



        Console.WriteLine($"Индексы {index.i} {index.j}");

        Console.ReadLine();

System.ValueTuple придется подключить

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.