Domanda

C'è un buon modo per enumerare solo un sottoinsieme di una collezione in C #? Cioè, ho una collezione di un gran numero di oggetti (ad esempio, 1000), ma mi piacerebbe per enumerare solo elementi 250 - 340. C'è un buon modo per ottenere un enumeratore per un sottoinsieme di raccolta, senza utilizzando un altro Collection?

Modifica:. Avrebbe dovuto detto che questo sta utilizzando .NET Framework 2.0

È stato utile?

Soluzione

Prova il seguente

var col = GetTheCollection();
var subset = col.Skip(250).Take(90);

o più in generale

public static IEnumerable<T> GetRange(this IEnumerable<T> source, int start, int end) {
  // Error checking removed
  return source.Skip(start).Take(end - start);
}

Modifica 2.0 Soluzione

public static IEnumerable<T> GetRange<T>(IEnumerable<T> source, int start, int end ) {
  using ( var e = source.GetEnumerator() ){ 
    var i = 0;
    while ( i < start && e.MoveNext() ) { i++; }
    while ( i < end && e.MoveNext() ) { 
      yield return e.Current;
      i++;
    }
  }      
}

IEnumerable<Foo> col = GetTheCollection();
IEnumerable<Foo> range = GetRange(col, 250, 340);

Altri suggerimenti

Mi piace mantenere le cose semplici (se non necessariamente bisogno l'enumeratore):

for (int i = 249; i < Math.Min(340, list.Count); i++)
{
    // do something with list[i]
}

L'adattamento codice originale di Jared per .Net 2.0:

IEnumerable<T> GetRange(IEnumerable<T> source, int start, int end)
{
    int i = 0;
    foreach (T item in source)
    {
        i++;
        if (i>end) yield break;
        if (i>start) yield return item;
    }
}

E per usarlo:

 foreach (T item in GetRange(MyCollection, 250, 340))
 {
     // do something
 }

L'adattamento del codice di Jarad, ancora una volta, questo metodo estensione ti porterà un sottoinsieme che è definito da elemento , non è indice.

    //! Get subset of collection between \a start and \a end, inclusive
    //! Usage
    //! \code
    //! using ExtensionMethods;
    //! ...
    //! var subset = MyList.GetRange(firstItem, secondItem);
    //! \endcode
class ExtensionMethods
{
    public static IEnumerable<T> GetRange<T>(this IEnumerable<T> source, T start, T end)
    {
#if DEBUG
        if (source.ToList().IndexOf(start) > source.ToList().IndexOf(end))
            throw new ArgumentException("Start must be earlier in the enumerable than end, or both must be the same");
#endif
        yield return start;

        if (start.Equals(end))
            yield break;                                                    //start == end, so we are finished here

        using (var e = source.GetEnumerator())
        { 
            while (e.MoveNext() && !e.Current.Equals(start));               //skip until start                
            while (!e.Current.Equals(end) && e.MoveNext())                  //return items between start and end
                yield return e.Current;
        }
    }
}

Potreste essere in grado di fare qualcosa con LINQ. Il modo in cui vorrei farlo è quello di mettere gli oggetti in un array, allora posso scegliere quali elementi voglio processo basato sulla matrice id.

Se si scopre che è necessario fare una discreta quantità di affettare e sminuzzare di liste e raccolte, forse vale la pena salire la curva di apprendimento in C5 Generic Collezione Biblioteca .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top