Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / C#
Tip/Trick

SortedSet Linq Extension Method

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
25 Aug 2010CPOL 20K   3   4
This simple extension method allows you to create a SortedSet from a Linq query
.Net 4.0 brought us the SortedSet:
http://msdn.microsoft.com/en-us/library/dd412070.aspx[^]

This collection class is really handy as each item added to it is automatically placed at the appropriate location in the list so that the list remains sorted. In addition, the SortedSet handles all this with little to no affect on performance.

However, there is no extension method that allows you to write a Linq query and get the results in a SortedSet. Of course you can order a List using Linq, but the advantage of the SortedSet is that each item added to the list, before or after the Linq query is run, will automatically be placed in the correct location.

So, here's a simple extension method to return the results of a Linq query into a SortedSet:

public static SortedSet<T> ToSortedSet<T>(this IEnumerable<T> t)
{
    SortedSet<T> retval = new SortedSet<T>();

    t.ToList().ForEach(x => retval.Add(x));

    return retval;
}



And here's a sample of using it:

static void Main(string[] args)
{
    // Create some customer objects and add them to a SortedSet.         
    Customer cust1 = new Customer { CustomerName = "Wal Mart", CreditBalance = 525565.55M};
    Customer cust2 = new Customer { CustomerName = "Ziggy's"};
    Customer cust3 = new Customer { CustomerName = "Bill's Place", CreditBalance = 2545.18M };
    SortedSet<Customer> customers = new SortedSet<Customer>();
    customers.Add(cust1);
    customers.Add(cust2);
    customers.Add(cust3);

    // Query the sorted set using Linq 
    var custs = (from c in customers
                    select c).ToSortedSet();
    // Add an item to the result set. You will see that it appears first in the list
    custs.Add(new Customer { CustomerName = "Able's Axel Shop" });

    // Show the results
    foreach (Customer customer in custs)
        Console.WriteLine(customer.CustomerName);
    Console.ReadLine();
}


And finally, here's the Customer class. In the CompareTo you can decide
how the SortedSet will sort:

C#
public class Customer : IComparable
{
    public string CustomerName { get; set; }
    public DateTime? DateAdded { get; set; }
    public decimal? CreditBalance { get; set; }

    public int CompareTo(object obj)
    {
        if (obj is Customer)
        {
            Customer c = (Customer)obj;

            return CustomerName.CompareTo(c.CustomerName);
            //return CustomerName.CompareTo(c.CreditBalance.ToString());
        }
        else
            throw new ArgumentException("Object is not a Customer.");

    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Marois Consulting
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 1 new SortedSet( Pin
Magnus_18-Nov-10 3:19
Magnus_18-Nov-10 3:19 
GeneralReason for my vote of 5 Good one. Thanks for sharing Pin
Sivaraman Dhamodharan2-Nov-10 0:20
Sivaraman Dhamodharan2-Nov-10 0:20 
GeneralSo you didn't find it useful? Pin
Kevin Marois26-Oct-10 8:18
professionalKevin Marois26-Oct-10 8:18 
GeneralReason for my vote of 5 the 5 for doing this as a tip and no... Pin
TheyCallMeMrJames26-Oct-10 8:17
TheyCallMeMrJames26-Oct-10 8:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.