简体   繁体   中英

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.

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() 
                     };

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() };

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() };

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()}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM