简体   繁体   中英

How to use like Clause in C# LInQ

How would I use a like clause using the following LINQ snippet?:

var query = from r in document.Descendants("Employee")
                        where (string)r.Element("FirstName").Value == txtSearch.Text
                        select new
                        {

                            FirstName = r.Element("FirstName").Value,
                            Age = r.Element("Age").Value
                        }; 

I tried the following but it did not work:

var query = from r in document.Descendants("Employee")
                        where (string)r.Element("FirstName").Value.Contains(txtSearch.Text)
                        select new
                        {

                            FirstName = r.Element("FirstName").Value,
                            Age = r.Element("Age").Value
                        };

...thanks in advance for any assistance

You are trying to cast a boolean to an string:

where (string)r.Element("FirstName").Value.Contains(txtSearch.Text)

If Value really needs a cast to String the code should be this:

where ((string)r.Element("FirstName").Value).Contains(txtSearch.Text)

But I think you don't need it because if VS has completed Contains it's an string function and the cast isn't needed:

where r.Element("FirstName").Value.Contains(txtSearch.Text)

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