Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
List<int> types = new List<int>();
foreach (var d in myTableList)
    if (!types.Contains((int)d.item_type))

I have a table in db called myTable. There is a column in it called item_type. It is integer.

I want to make a list which would have all item_type which are in myTableList, but there shouldn't be duplicates.

I tried:

types = myTableList.Distinct(x => x.item_type)

but I want types to be list of integers, not items of type myTable.

share|improve this question
up vote 7 down vote accepted


types = myTableList
    .Select(x => (int)x.item_type)

You may also want to add .ToList() at the end if you want to match original code

share|improve this answer

Another option is to just use a HashSet<T> to do the distinction for you:

var types = new HashSet<int>(myTableList.Select(x => (int)x.item_type)).ToList();
share|improve this answer
Distinct does exactly that – almaz Feb 2 '13 at 9:21
Just to expand my previous comment... Distinct uses HashSet to ensure uniqueness of elements, and outputs element if it has not been seen before. – almaz Feb 2 '13 at 10:10
Yes, hence why I said "another option". – OJ. Feb 2 '13 at 22:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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