简体   繁体   中英

LINQ queries for List Objects in C#

I have the following object

 public partial class LookUP 
{
    public int Id { get; set; } //this is like a primary key.
    public string LookUpSchema { get; set; }
    public string LookUpColumn { get; set; }
    public string LookUpValue { get; set; }
    public DateTime? DateModified { get; set; }
}

This object maps to an entity object in the database. Some values in the table are :

Id LookUpSchema LookUpColumn LookUpValue DateModified
1 LDAP State TN NULL
2 LDAP State MH NULL
3 LDAP State DL NULL
4 LDAP ACCOUNT A NULL
5 LDAP ACCOUNT B NULL
6 LDAP ACCOUNT C NULL
7 LDAP LANGUAGE EN NULL
8 LDAP LANGUAGE FR NULL

when querying over database its easy to get the values as they are indexed, some queries like

 select * from tablename where lookupschema='LDAP' and LookUpColumn ='State' 

will yield all values TN, MH,DL

select * from tablename where lookupschema='LDAP' and LookUpColumn  ='LANGUAGE' 

will yield all values EN, FR

DUE to some reasons we cannot be querying the table all the time. So first time we query the lookuptable and get all its values and store it in the Lookuplist.

    List<LookUP> lookuplist = new List<LookUP>();
     LookUP LOOKUP = new LookUP()
        {
            Id = 1,

             LookUpColumn="STATE",
              LookUpSchema="LDAP",
              LookUpValue="TN"
            
        };
       lookuplist.Add(LOOKUP);

Now that I have all the values in the lookuplist Can I write equivalent linq queries or functions for this? instead of querying database I have to query list<>

   select * from tablename where lookupschema='LDAP' and LookUpColumn   ='State' 

You can query the list directly:

var results = lookuplist.Where(e => e.LookUpSchema =="LDAP" && e.LookUpColumn   == "STATE");

You can also use more "sql" approach with using from and where. There is good example in Microsoft's documentation for LINQ: https://docs.microsoft.com/en-us/dotnet/csharp/linq/query-a-collection-of-objects

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