Appending/concatenating two IEnumerable sequences

后端 未结 4 1720
渐次进展
渐次进展 2020-12-15 15:01

I have two sets of datarows. They are each IEnumerable. I want to append/concatenate these two lists into one list. I\'m sure this is doable. I don\'t want to do a for loop

4条回答
  •  隐瞒了意图╮
    2020-12-15 15:42

    I just encountered a similar situation where I need to concatenate multiple sequences.

    Naturally searched for existing solutions on Google/StackOverflow, however did not find anything the did not evaluate the enumerable, e.g. convert to array then use Array.Copy() etc., so I wrote an extension and static utiltiy method called ConcatMultiple.

    Hope this helps anyone that needs to do the same.

    /// 
    /// Concatenates multiple sequences
    /// 
    /// The type of the elements of the input sequences.
    /// The first sequence to concatenate.
    /// The other sequences to concatenate.
    /// 
    public static IEnumerable ConcatMultiple(this IEnumerable first, params IEnumerable[] source)
    {
        if (first == null)
            throw new ArgumentNullException("first");
    
        if (source.Any(x => (x == null)))
            throw new ArgumentNullException("source");
    
        return ConcatIterator(source);
    }
    
    private static IEnumerable ConcatIterator(IEnumerable first, params IEnumerable[] source)
    {
        foreach (var iteratorVariable in first)
            yield return iteratorVariable;
    
        foreach (var enumerable in source)
        {
            foreach (var iteratorVariable in enumerable)
                yield return iteratorVariable;
        }
    }
    
    /// 
    /// Concatenates multiple sequences
    /// 
    /// The type of the elements of the input sequences.        
    /// The sequences to concatenate.
    /// 
    public static IEnumerable ConcatMultiple(params IEnumerable[] source)
    {
        if (source.Any(x => (x == null)))
            throw new ArgumentNullException("source");
    
        return ConcatIterator(source);
    }
    
    private static IEnumerable ConcatIterator(params IEnumerable[] source)
    {
        foreach (var enumerable in source)
        {
            foreach (var iteratorVariable in enumerable)
                yield return iteratorVariable;
        }
    }
    

提交回复
热议问题