Scorrere due elenchi o matrici con un'istruzione ForEach in C #


142

Questo solo per conoscenza generale:

Se ne ho due, diciamo, Elenco , e voglio iterare entrambi con lo stesso ciclo foreach, possiamo farlo?

modificare

Giusto per chiarire, volevo fare questo:

List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };

for(int i = 0; i < listA.Count; i++)
    listB[i] = listA[i];

Ma con un foreach =)


10
La parola importante qui è "zip".
Mark Byers,

3
Vuoi iterare due liste in parallelo ? Oppure vuoi iterare prima un elenco e poi l'altro (con una singola istruzione)?
Pavel Minaev,

Penso che la tua strada sia migliore della zip
Alexander,

Risposte:


275

Questa operazione è nota come operazione Zip e sarà supportata in .NET 4.

Con ciò, saresti in grado di scrivere qualcosa del tipo:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

In alternativa al tipo anonimo con i campi con nome, puoi anche salvare le parentesi graffe utilizzando una Tupla e la sua Tupla statica.

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}


2
Non sapevo nulla di quelle operazioni Zip, farò una piccola ricerca su questo argomento. Grazie!
Hugo,

4
@Hugo: è un costrutto standard nella programmazione funzionale :)
Mark Seemann,

Sarà inoltre necessario utilizzare System.Linq;
Jahmic,

5
Dal momento che C # 7, si potrebbe anche usare un ValueTuple (vedi stackoverflow.com/a/45617748 ) al posto di tipi anonimi o Tuple.Create. Vale a dire foreach ((var number, var word) in numbers.Zip(words, (n, w) => (n, w))) { ... }.
Erlend Graff,

14

Se non si desidera attendere .NET 4.0, è possibile implementare il proprio Zipmetodo. Di seguito funziona con .NET 2.0. È possibile regolare l'implementazione in base a come si desidera gestire il caso in cui le due enumerazioni (o elenchi) hanno lunghezze diverse; questo continua fino alla fine dell'enumerazione più lunga, restituendo i valori predefiniti per gli elementi mancanti dall'enumerazione più breve.

static IEnumerable<KeyValuePair<T, U>> Zip<T, U>(IEnumerable<T> first, IEnumerable<U> second)
{
    IEnumerator<T> firstEnumerator = first.GetEnumerator();
    IEnumerator<U> secondEnumerator = second.GetEnumerator();

    while (firstEnumerator.MoveNext())
    {
        if (secondEnumerator.MoveNext())
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, secondEnumerator.Current);
        }
        else
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, default(U));
        }
    }
    while (secondEnumerator.MoveNext())
    {
        yield return new KeyValuePair<T, U>(default(T), secondEnumerator.Current);
    }
}

static void Test()
{
    IList<string> names = new string[] { "one", "two", "three" };
    IList<int> ids = new int[] { 1, 2, 3, 4 };

    foreach (KeyValuePair<string, int> keyValuePair in ParallelEnumerate(names, ids))
    {
        Console.WriteLine(keyValuePair.Key ?? "<null>" + " - " + keyValuePair.Value.ToString());
    }
}

1
Bel metodo! :). È possibile fare qualche aggiustamento per usare la stessa firma .NET 4 Zip metodo msdn.microsoft.com/en-us/library/dd267698.aspx e resultSelector ritorno (primo, secondo) al posto di un KVP.
Martín Coll,

Si noti che questo metodo non dispone i suoi enumeratori che potrebbero diventare un problema, ad esempio se viene utilizzato con gli enumerabili sulle righe dei file aperti.
Lii

11

Puoi usare Union o Concat, il primo rimuove i duplicati, il secondo no

foreach (var item in List1.Union(List1))
{
   //TODO: Real code goes here
}

foreach (var item in List1.Concat(List1))
{
   //TODO: Real code goes here
}

Un altro problema con l'uso di un'Unione è che può buttare via le istanze se valutano come uguali. Potrebbe non essere sempre quello che vuoi.
Mark Seemann,

1
Intendo che la sua intenzione fosse quella di usare collezioni dello stesso tipo,
albertein il

@Mark Seemann, ho già sottolineato che, potrebbe anche usare Concat
albertein

Come Union, Concat funziona solo se entrambi gli elenchi sono dello stesso tipo. Non riesco a capire se questo è ciò di cui l'OP ha bisogno o meno, però ...
Mark Seemann,

Questo crea un nuovo elenco che contiene tutti gli elementi. Questo è uno spreco di memoria. Utilizzare invece Linq Concat.
Drew Noakes,

3

Ecco un metodo di estensione IEnumerable <> personalizzato che può essere utilizzato per scorrere simultaneamente due elenchi.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public static class LinqCombinedSort
    {
        public static void Test()
        {
            var a = new[] {'a', 'b', 'c', 'd', 'e', 'f'};
            var b = new[] {3, 2, 1, 6, 5, 4};

            var sorted = from ab in a.Combine(b)
                         orderby ab.Second
                         select ab.First;

            foreach(char c in sorted)
            {
                Console.WriteLine(c);
            }
        }

        public static IEnumerable<Pair<TFirst, TSecond>> Combine<TFirst, TSecond>(this IEnumerable<TFirst> s1, IEnumerable<TSecond> s2)
        {
            using (var e1 = s1.GetEnumerator())
            using (var e2 = s2.GetEnumerator())
            {
                while (e1.MoveNext() && e2.MoveNext())
                {
                    yield return new Pair<TFirst, TSecond>(e1.Current, e2.Current);
                }
            }

        }


    }
    public class Pair<TFirst, TSecond>
    {
        private readonly TFirst _first;
        private readonly TSecond _second;
        private int _hashCode;

        public Pair(TFirst first, TSecond second)
        {
            _first = first;
            _second = second;
        }

        public TFirst First
        {
            get
            {
                return _first;
            }
        }

        public TSecond Second
        {
            get
            {
                return _second;
            }
        }

        public override int GetHashCode()
        {
            if (_hashCode == 0)
            {
                _hashCode = (ReferenceEquals(_first, null) ? 213 : _first.GetHashCode())*37 +
                            (ReferenceEquals(_second, null) ? 213 : _second.GetHashCode());
            }
            return _hashCode;
        }

        public override bool Equals(object obj)
        {
            var other = obj as Pair<TFirst, TSecond>;
            if (other == null)
            {
                return false;
            }
            return Equals(_first, other._first) && Equals(_second, other._second);
        }
    }

}

3

Da C # 7, puoi usare Tuple ...

int[] nums = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three", "four" };

foreach (var tuple in nums.Zip(words, (x, y) => (x, y)))
{
    Console.WriteLine($"{tuple.Item1}: {tuple.Item2}");
}

// or...
foreach (var tuple in nums.Zip(words, (x, y) => (Num: x, Word: y)))
{
    Console.WriteLine($"{tuple.Num}: {tuple.Word}");
}

1
Cosa succede quando le due liste non hanno la stessa lunghezza in questa situazione?
John August

Con (x, y) => (x, y)possiamo usare il nome tuple.xe tuple.yche è elegante. Quindi anche il secondo modulo potrebbe essere(Num, Word) => (Num, Word)
preciso il

2
@JohnAugust Termina dopo aver attraversato la sequenza più breve. Dai documenti: "Se le sequenze non hanno lo stesso numero di elementi, il metodo unisce le sequenze fino a quando non ne raggiunge la fine. Ad esempio, se una sequenza ha tre elementi e l'altra ne ha quattro, la sequenza dei risultati sarà hanno solo tre elementi ".
Gregsmi,

0

No, per questo dovresti usare un for-loop.

for (int i = 0; i < lst1.Count; i++)
{
    //lst1[i]...
    //lst2[i]...
}

Non puoi fare qualcosa del genere

foreach (var objCurrent1 int lst1, var objCurrent2 in lst2)
{
    //...
}

E se hanno conteggi diversi?
Drew Noakes,

Quindi una foreach che accetterebbe un elenco arbitrario di enumerabili non funzionerebbe altrettanto bene, rendendo così il tutto inutile.
Maximilian Mayerl,

0

Se vuoi un elemento con quello corrispondente, puoi farlo

Enumerable.Range(0, List1.Count).All(x => List1[x] == List2[x]);

Ciò restituirà true se ogni elemento è uguale a quello corrispondente nel secondo elenco

Se questo è quasi ma non esattamente quello che vuoi, sarebbe utile se tu elaborassi di più.


0

Questo metodo funzionerebbe per un'implementazione dell'elenco e potrebbe essere implementato come metodo di estensione.

public void TestMethod()
{
    var first = new List<int> {1, 2, 3, 4, 5};
    var second = new List<string> {"One", "Two", "Three", "Four", "Five"};

    foreach(var value in this.Zip(first, second, (x, y) => new {Number = x, Text = y}))
    {
        Console.WriteLine("{0} - {1}",value.Number, value.Text);
    }
}

public IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(List<TFirst> first, List<TSecond> second, Func<TFirst, TSecond, TResult> selector)
{
    if (first.Count != second.Count)
        throw new Exception();  

    for(var i = 0; i < first.Count; i++)
    {
        yield return selector.Invoke(first[i], second[i]);
    }
}

0

Puoi anche semplicemente usare una variabile intera locale se le liste hanno la stessa lunghezza:

List<classA> listA = fillListA();
List<classB> listB = fillListB();

var i = 0;
foreach(var itemA in listA)
{
    Console.WriteLine(itemA  + listB[i++]);
}

-1

Puoi anche fare quanto segue:

var i = 0;
foreach (var itemA in listA)
{
  Console.WriteLine(itemA + listB[i++]);
}

Nota: la lunghezza di listAdeve essere la stessa di listB.


-3

Comprendo / spero che le liste abbiano la stessa lunghezza: No, la tua unica scommessa sta andando con un semplice vecchio standard per il loop.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.