MindGame
MindGame

Reputation: 1251

Limit results from linq results .NET

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

Answers (4)

jhilden
jhilden

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

driis
driis

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

Cameron
Cameron

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

Mark Cidade
Mark Cidade

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

Related Questions