Home > OS >  How can i check if a column value is in a table using c#?
How can i check if a column value is in a table using c#?

Time:09-24

I have a table with a column name "FileName" and my file is Tesfile.txt and there are 10 rows . Is there a way i can check if any row in the table has the value Testfile.txt in the column "FileName" ? I am using something like

if ( table.Columns["SourceFile"][0] == "Testfile.txt")
{
   //do whatever
}

but can i do it simply with linq ?

CodePudding user response:

if (table.AsEnumerable().Any(row => "Testfile.txt" == row.Field<String>("SourceFile"))) 
{
    // do whatever
}

if you want to do the opposite (None instead of Any), you can do this

if (!table.AsEnumerable().Any(row => "Testfile.txt" == row.Field<String>("SourceFile"))) 
{
    // do whatever
}

Or even add this and use None directly:

public static bool None<TSource>(this IEnumerable<TSource> source)
{
    return !source.Any();
}

public static bool None<TSource>(this IEnumerable<TSource> source, 
                                 Func<TSource, bool> predicate)
{
    return !source.Any(predicate);
}
  •  Tags:  
  • c#
  • Related