I'm able to loop through a list on sharepoint and get the information I need from selected columns, but how would I loop through a list and get only distinct values from a column in C#. For instance lets get all the distinct values from a the email column?

I know I can foreach through the list

foreach (SPListItem item in List.getItems(querysp)
var itemID = item.ID;
var itemEmail = item["email"];

//more vars here



2 Answers 2


You can get Distinct values for email column from your SharePoint list using below mentioned code. i had showed how to insert the distinct email values in drop down list. you can change the code accordingly.

 SPList oList = SPContext.Current.Web.Lists["Your List Nmae Here"];
 SPQuery query = new SPQuery();
 query.Query = "<OrderBy><FieldRef Name='Email' /></OrderBy>";
 DataTable dtcamltest = oList.GetItems(query).GetDataTable();
 DataView dtview = new DataView(dtcamltest);
 DataTable dtdistinct = dtview.ToTable(true, "Email");
 ddl_names.DataSource = dtdistinct; 
 ddl_names.DataTextField = "Email";
 ddl_names.DataValueField = "Email";
catch (Exception exe)
 Response.Write("Exception at btn_binddropdown_Click :" + exe);

I don't know if it is possible with CAML, but this should work:

var emails = List.getItems(querysp).OfType<SPListItem>().Select(item => "" + item["email"]).Distinct();
  • whenever I post the values from emails into the console. I get the following value "System.Linq.Enumerable+<DistinctIterator>d__81'1[System.String" It's posted 5 times (number of items in the list is 5 when it should only be posted 3 times since there are only 3 unique emails) am I doing something wrong?
    – zingwing
    Apr 1, 2015 at 17:25
  • You get an IEnumerable back. You could try ToList(), even ...Distinct().ToList().ForEach(Console.WriteLine)
    – eirikb
    Apr 1, 2015 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.