This code snippet shows how to get distinct values from a list column using IEnumerable interface.
For example, I have a column called “CarMake” and it contains user defined values and need to get distinct values of all car makes.


// Get Links where Collection is EMPTY (get Distinct)
SPQuery oQuery = new SPQuery();
oQuery.Query = "";
oQuery.ViewFields = "";
SPListItemCollection itemColl = oList.GetItems(oQuery);

// Get Distinct values from CarMake and Sort
IEnumerable distinctList = itemColl.Cast()
    .Select(item => item["CarMake"].ToString())
    .OrderBy(item => item["CarMake"])
    .Distinct();

// Loop through each value
using (IEnumerator enumerator = distinctList.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        string tempStr = enumerator.Current.ToString();
    }
}
Advertisements