Reputation: 1251
I am using linq to get a list of results from an enumeration list. Right now I am returning the full list.
Doing the following:
ViewData["listDT"] = from c in Enum.GetValues(typeof(ColumnDataType)).Cast<ColumnDataType>().ToList()
select new SelectListItem { Value = c.ToString(), Text = c.ToString() };
Where my ColumnDateType enumeration is:
public enum ColumnDataType
{
String,
Date,
DateTime,
Integer,
Decimal,
MultipleChoice,
PictureBox,
Attachment,
Boolean,
AutoNumber
}
My question is how do I make it so that I only return String, DateTime, Decimal and Integer using my current Linq statement.
Upvotes: 0
Views: 120
Reputation: 12429
There are cleaner ways to do this to be sure, but a simple way would be adding a where clause.
from c in Enum.GetValues(typeof(ColumnDataType)).Cast<ColumnDataType>().ToList()
where c == ColumnDataType.String
|| c == ColumnDataType.DateTime
|| c == ColumnDataType.Decimal
select new SelectListItem { Value = c.ToString(), Text = c.ToString() };
One thing to consider: if you know the values you want to add why not do something like this instead:
var availableValues = new List<SelectListItem> {
new SelectListItem {Value = ColumnDataType.String.ToString()},
new SelectListItem {Value = ColumnDataType.DateTime.ToString()}
new SelectListItem {Value = ColumnDataType.Decimal.ToString()}
}
Upvotes: 2
Reputation: 164291
If you already know the list of values you want, just use that as the source:
from c in new [] {ColumnDataType.String, ColumnDataType.DateTime, ColumnDataType.Decimal, ColumnDataType.Integer}
select new SelectListItem { Value = c.ToString(), Text = c.ToString() };
Upvotes: 3
Reputation: 2594
If you only want those specified values, try something like this:
ViewData["listDT"] = from c in new[]
{
ColumnDataType.String,
ColumnDataType.DateTime,
ColumnDataType.Decimal,
ColumnDataType.Integer
}
select new SelectListItem
{
Value = c.ToString(),
Text = c.ToString()
};
Upvotes: 6
Reputation: 99957
You can use a where
clause to filter your results:
ViewData["listDT"] = from c in Enum.GetValues(typeof(ColumnDataType)).Cast<ColumnDataType>().ToList()
where c == ColumnDataType.String
|| c == ColumnDataType.DateTime
|| c == ColumnDataType.Decimal
|| c == ColumnDataType.Integer
select new SelectListItem { Value = c.ToString(), Text = c.ToString() };
Upvotes: 3