Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing 'CONTAINS' query using LINQ

Given the output of query:

var queryResult = from o in objects
                  where ...
                  select new 
                      {
                         FileName = o.File,
                         Size = o.Size
                      }

What would you consider the neatest way to detect if a file is in the queryResult? Here is my lame try with LINQ:

string searchedFileName = "hello.txt";
var hitlist = from file in queryResult
              where file.FileName == searchedFileName
              select file;
var contains = hitlist.Count() > 0;

There must be an more elegant way to figure out the result.

like image 707
user256890 Avatar asked Mar 04 '10 12:03

user256890


People also ask

How use contains in LINQ query?

To check for an element in a string, use the Contains() method. The following is our string array. string[] arr = { "Java", "C++", "Python"}; Now, use Contains() method to find a specific string in the string array.

How to write LINQ queries in C#?

There are the following two ways to write LINQ queries using the Standard Query operators, in other words Select, From, Where, Orderby, Join, Groupby and many more. Using lambda expressions. Using SQL like query expressions.


1 Answers

string searchedFileName = "hello.txt";
var contains = queryResult.Any(file => file.FileName == searchedFileName);
like image 152
Yaakov Ellis Avatar answered Oct 28 '22 08:10

Yaakov Ellis