Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 764071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T16:39:48+00:00 2026-05-14T16:39:48+00:00

I have several huge sorted enumerable sequences that I want to merge . Theses

  • 0

I have several huge sorted enumerable sequences that I want to merge. Theses lists are manipulated as IEnumerable but are already sorted. Since input lists are sorted, it should be possible to merge them in one trip, without re-sorting anything.

I would like to keep the defered execution behavior.

I tried to write a naive algorithm which do that (see below). However, it looks pretty ugly and I’m sure it can be optimized. It may exist a more academical algorithm…

IEnumerable<T> MergeOrderedLists<T, TOrder>(IEnumerable<IEnumerable<T>> orderedlists, 
                                            Func<T, TOrder> orderBy)
{
    var enumerators = orderedlists.ToDictionary(l => l.GetEnumerator(), l => default(T));
    IEnumerator<T> tag = null;

    var firstRun = true;
    while (true)
    {
        var toRemove = new List<IEnumerator<T>>();
        var toAdd = new List<KeyValuePair<IEnumerator<T>, T>>();
        foreach (var pair in enumerators.Where(pair => firstRun || tag == pair.Key))
        {
            if (pair.Key.MoveNext())
                toAdd.Add(pair);
            else
                toRemove.Add(pair.Key);
        }

        foreach (var enumerator in toRemove)
            enumerators.Remove(enumerator);

        foreach (var pair in toAdd)
            enumerators[pair.Key] = pair.Key.Current;

        if (enumerators.Count == 0)
            yield break;

        var min = enumerators.OrderBy(t => orderBy(t.Value)).FirstOrDefault();
        tag = min.Key;
        yield return min.Value;

        firstRun = false;
    }
}

The method can be used like that:

// Person lists are already sorted by age
MergeOrderedLists(orderedList, p => p.Age);

assuming the following Person class exists somewhere:

    public class Person
    {
        public int Age { get; set; }
    }

Duplicates should be conserved, we don’t care about their order in the new sequence. Do you see any obvious optimization I could use?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T16:39:49+00:00Added an answer on May 14, 2026 at 4:39 pm

    Here is my fourth (thanks to @tanascius for pushing this along to something much more LINQ) cut at it:

    public static IEnumerable<T> MergePreserveOrder3<T, TOrder>(
        this IEnumerable<IEnumerable<T>> aa,
        Func<T, TOrder> orderFunc)
    where TOrder : IComparable<TOrder>
    {
        var items = aa.Select(xx => xx.GetEnumerator()).Where(ee => ee.MoveNext())
            .OrderBy(ee => orderFunc(ee.Current)).ToList();
    
        while (items.Count > 0)
        {
            yield return items[0].Current;
    
            var next = items[0];
            items.RemoveAt(0);
            if (next.MoveNext())
            {
                // simple sorted linear insert
                var value = orderFunc(next.Current);
                var ii = 0;
                for ( ; ii < items.Count; ++ii)
                {
                    if (value.CompareTo(orderFunc(items[ii].Current)) <= 0)
                    {
                        items.Insert(ii, next);
                        break;
                    }
                }
    
                if (ii == items.Count) items.Add(next);
            }
            else next.Dispose(); // woops! can't forget IDisposable
        }
    }
    

    Results:

    for (int p = 0; p < people.Count; ++p)
    {
        Console.WriteLine("List {0}:", p + 1);
        Console.WriteLine("\t{0}", String.Join(", ", people[p].Select(x => x.Name)));
    }
    
    Console.WriteLine("Merged:");
    foreach (var person in people.MergePreserveOrder(pp => pp.Age))
    {
        Console.WriteLine("\t{0}", person.Name);
    }
    
    List 1:
            8yo, 22yo, 47yo, 49yo
    List 2:
            35yo, 47yo, 60yo
    List 3:
            28yo, 55yo, 64yo
    Merged:
            8yo
            22yo
            28yo
            35yo
            47yo
            47yo
            49yo
            55yo
            60yo
            64yo
    

    Improved with .Net 4.0’s Tuple support:

    public static IEnumerable<T> MergePreserveOrder4<T, TOrder>(
        this IEnumerable<IEnumerable<T>> aa,
        Func<T, TOrder> orderFunc) where TOrder : IComparable<TOrder>
    {
        var items = aa.Select(xx => xx.GetEnumerator())
                      .Where(ee => ee.MoveNext())
                      .Select(ee => Tuple.Create(orderFunc(ee.Current), ee))
                      .OrderBy(ee => ee.Item1).ToList();
    
        while (items.Count > 0)
        {
            yield return items[0].Item2.Current;
    
            var next = items[0];
            items.RemoveAt(0);
            if (next.Item2.MoveNext())
            {
                var value = orderFunc(next.Item2.Current);
                var ii = 0;
                for (; ii < items.Count; ++ii)
                {
                    if (value.CompareTo(items[ii].Item1) <= 0)
                    {   // NB: using a tuple to minimize calls to orderFunc
                        items.Insert(ii, Tuple.Create(value, next.Item2));
                        break;
                    }
                }
    
                if (ii == items.Count) items.Add(Tuple.Create(value, next.Item2));
            }
            else next.Item2.Dispose(); // woops! can't forget IDisposable
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose that you have two huge files (several GB) that you want to concatenate
I have a quite huge Java class that has several imported packages and libraries
I have a rather huge query that is needed in several stored procedures, and
I have several (27) huge (several GB each) bz2 archive files that I need
I have a huge form (for an internal CMS) that is comprised by several
I have a huge table in a database and I want to split that
I have several xml files with different node structure. I want to extract xml
I have several HTML elements (buttons) that fire the same JQuery AJAX request. When
I have several Delphi programs that maintain connections to a database (some Oracle, some
I have several different numbers in a group that range in sizes and would

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.