1
\$\begingroup\$
List<int> types = new List<int>();
foreach (var d in myTableList)
{
    if (!types.Contains((int)d.item_type))
        types.Add((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.

\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

Try

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

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

\$\endgroup\$
1
\$\begingroup\$

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();
\$\endgroup\$
3
  • \$\begingroup\$ Distinct does exactly that \$\endgroup\$ Commented Feb 2, 2013 at 9:21
  • \$\begingroup\$ Just to expand my previous comment... Distinct uses HashSet to ensure uniqueness of elements, and outputs element if it has not been seen before. \$\endgroup\$ Commented Feb 2, 2013 at 10:10
  • \$\begingroup\$ Yes, hence why I said "another option". \$\endgroup\$ Commented Feb 2, 2013 at 22:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.