简体   繁体   中英

Dynamic LINQ in c#

Hey i am making a simple search machine through alot of different coloumns in 2 tables.

I was trying to get this to abit dynamical.

I read this:

Is there a pattern using Linq to dynamically create a filter?

Which is something that really could do the trick for me.. its just in VB and i need it in c#

here is my code :

private void displayWith1Criteria(string column, string value)
{
    Console.WriteLine("entering _1_ display method");
    dbcontent = new DBtestEntities();
    var studienummerQuery = from members in dbcontent.Medlemmer.Include("Retninger")
                            where column == value
                            orderby members.Fornavn
                            select new { Studienr = members.Studienummer, Fornavn = members.Fornavn, Efternavn = members.Efternavn, Email = members.Email, Studiested = members.Studiested, Betaling = members.BetalingsType, Uddannelses_Retning = members.Retninger.retningNavn };

    dataGridView1.DataSource = studienummerQuery;
}

Doesn't return any data at all...

column is being called with members.Fornavn (Fornavn - a column name)

value = Anders (one of the data's in Fornavn column)

What I want to do: My database is loaded into dbcontent using a .edmx file from ABO entity class. My database consist of 2 tables, "Retninger" and "Medlemmer". Medlemmer contains columns things like Fornavn(in english, Firstname), Efternavn(Lastname), Studienummer(study no.) What i would like is a "dynamic" method that can set both which column to be searched in and the value that needs to be searched for in the set column.

I think this answer from Shawn Miller to the question you linked is more what you are looking for:

http://www.albahari.com/nutshell/predicatebuilder.html

When could your expression column == value possibly return true? Only if string.Equals("Fornavn", "Anders") is true.

Doing dynamic linq is hard. Is usually do it this way:

...
where (!useMycolumn1 || member.mycolumn1 == value1) 
    &&(!useMycolumn2 || member.mycolumn2 == value2) 
    &&(!useMycolumn3 || member.mycolumn3 == value3) 
...

useMycolumn* is a local boolean variable which is set to true or false, depending on whether the certain condition should be tested or not. This way, unused parts of the query are optimized out at compile time.

Are you remembring to call the DataBind() method on the grid? How do you know nothing is being returned?

I think its because of lazy evaluation of LINQ queries. You can try using .ToList, as below:

dataGridView1.DataSource = studienummerQuery.ToList();

also .DataBind(), if relevant for your object.

Edit:

Lazy Evaluation: This Link , would serve as a good start

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