Is LINQ the equivalent of the following code?

I am involved in the LINQ learning process and would like to help in the following method. How to rewrite the following method to use LINQ?

private bool IsInList(string file, List<FileInfo> excelList)
{
    if (excelList != null && excelList.Count > 0)
    {
        foreach (FileInfo f in excelList)
        {
            if (string.Compare(f.FullName, file, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return true;
            }
        }
    }

    return false;
}
+3
source share
5 answers

I would change the second parameter to accept IEnumerable<FileInfo>instead, so that you are not limited to lists only.

private bool IsInList(string file, IEnumerable<FileInfo> excelList)
{
    return excelList != null && excelList.Any(f => f.FullName.Equals(file, StringComparison.OrdinalIgnoreCase));
}
+7
source

Using lambdas:

private bool IsInList(string file, List<FileInfo> excelList)
{
    return excelList != null && excelList.Any(f => string.Compare(f.FullName, file, StringComparison.OrdinalIgnoreCase) == 0);
}
+3
source

Something like that:

private bool IsInList(string file, List<FileInfo> excelList)
{
    if (excelList == null) return false;
    return excelList.Any(f => string.Compare(f.FullName, file, StringComparison.OrdinalIgnoreCase) == 0));
}
+1
source

Give this try - completely untested.

private bool IsInList(string file, List<FileInfo> excelList)
{
    if (excelList != null && excelList.Count > 0)
    {
        return excelList.Any(f => string.Compare(f.FullName, file, StringComparison.OrdinalIgnoreCase) == 0);
    }

    return false;
}
0
source

It must...

if (excelList != null && excelList.Count > 0)
{
    return (from f in excelList
            where (string.Compare(f.FullName, file, StringComparison.OrdinalIgnoreCase) == 0)
            select f).Any();
}
return false;
0
source

All Articles