Search code examples
c#linqaspnetboilerplate

How can I get just the entries that match one condition?


I want to check if there in my table are entries that match my condition, I mean, I have this :

   [Required, MinLength(10), MaxLength(100)]
    public string Title { get; set; }
    [Required, MinLength(10), MaxLength(240)]
    public string Description { get; set; }
    [Required]
    public Metric Metric { get; set; }
    [Required]
    public float InitialValue { get; set; }
    [Required]
    public float TargetValue { get; set; }

    public bool KeyTaskCheck { get; set; }

I want to get all the entries that KeyTaskCheck = true, how can i Do that with Asp.net Boilerplate


Solution

  • I don't know Asp.net Boilerplate. Luckily you do, and you know how to extract data from it:

    IEnumerable<TableRow> myTableRows = ...
    

    (or IQueryable, or List, etc)

    TableRow is a class with the properties you wrote in your question. It represents one item of the fetched sequence of items. One of the properties of TableRow is the Boolean property KeyTaskCheck

    From my sequence of TableRow objects in myTableRows, give me only those that have a true value for property KeyTaskCheck.

    Whenever you have an IEnumerable / IQueryable sequence of similar objects, and you want to keep only those object that match some predicate, you should use Enumerable.Where

    It is helpful to use plural nouns as identifiers for sequences, and singular nouns as identifier for one element in the sequence.

    var result = myTableRows.Where(tableRow => tableRow.KeyTaskCheck);
    

    In words: from the sequence of TableRow objects in myTableRows, keep only those TableRow objects that have a true value for property KeyTaskCheck.

    The part x => F(x) in a LINQ statements, means: from every object xxx in the sequence of objects, call F(x).

    In case of a Where, the object will remain in the resulting sequence if and only if F(x) returns a true value.

    So if you wanted all TableRows that have a Title starting with an "A", and an InitialValue smaller than 1.0, your query would be:

    var result = myTableRows
        .Where(tableRow => tableRow.Title.StartsWith("A") && tableRow.InitialValue < 1.0);
    

    This article really helped me to understand LINQ