Tuesday, June 1, 2010

Query Operator First

Let's say you have the following method that returns a FileInfo object from an array if the Name property equals a certain value:
public static FileInfo FindFile(FileInfo[] fileInfoArray, string name)
{           
    foreach (FileInfo fi in fileInfoArray)
    {
        if (fi.Name == name)
            return fi;
    }
    return null;
}
You can replace this method with a call to the query operator First :

FileInfo fileInfo = fileInfoArray.First(fi => fi.Name =="myFileName.txt");
Since the query operator First returns a single value, it forces immediate query evaluation.

No comments:

Post a Comment