0

What would be the syntax for putting an array of integers into rows of a DataTable? I know how to do this via a foreach statement, but thought it may be more efficient to do this via LINQ instead. This is what I wrote, but imagine there may be a way to replace the foreach with a LINQ statement.

public static void saveThis(int mainID, int[] userIDList)
{
    // The DataTable represents a User-Defined Table Type (IdPair) that
    // contains 2 columns of StaticID and VariableID.
    DataTable dataTable = new DataTable("IdPair"); 
    dataTable.Columns.Add("StaticID");   // For the mainID
    dataTable.Columns.Add("VariableID"); // For the UserIDs
    foreach(int userID in userIDList)
    {
        dataTable.Rows.Add(mainID, userID);
    }

    // Omitted code to pass dataTable as a Structured object
    // to a stored procedure and save changes.
}

Can LINQ replace that foreach statement, and if so, how? Thanks for your help.

=== Edit 3/18/2015 at 1:25 PM Central ===

Thanks everyone for your quick feedback and insight. My apologies for the duplicate. Searches that I performed didn't turn anything up for this (e.g. "linq to put integer array into datatable"). This point I was unaware of, "Basically LINQ is for querying the data not modifying it". Given that, it makes no sense to use LINQ.

A moderator can close this. Thanks.

Ken Palmer
  • 2,355
  • 5
  • 37
  • 57
  • 1
    Basically LINQ is for querying the data not modifying it. You can rewrite it with LINQ but it will be more ugly. – abatishchev Mar 18 '15 at 18:09
  • However you can use `List.ForEach()` to simplify the code. But then you need to declare `List userIDList` or write own extension method `void ForEach(this IEnumerable seq)`. – abatishchev Mar 18 '15 at 18:10
  • 1
    @abatishchev He could just call `userIDList.ToList().ForEach()`, but I wouldn't recommend it. – JLRishe Mar 18 '15 at 18:11
  • @JLRishe That's not using LINQ. – Servy Mar 18 '15 at 18:12
  • @Servy `.ToList()` is LINQ, but my point was simply that one doesn't need to declare a new variable, change their method signature, or create an extension method to use `.ForEach()`. I wasn't talking about LINQ. – JLRishe Mar 18 '15 at 18:14
  • Thanks for the quick feedback. My apologies for the duplicate. Searches that I performed didn't turn anything up for this (e.g. "linq to put integer array into datatable"). This point I was unaware of, "Basically LINQ is for querying the data not modifying it". Given that, it makes no sense to use LINQ. Thanks everyone. – Ken Palmer Mar 18 '15 at 18:19

0 Answers0