0

I am trying to create a new row when I have the filtered results of a linq query. I want the syntax to be something like the following, but I don't know what to do. I am trying to create a new row with a selection of different fields from the old row.

dv = (from row in MV.Data.AsEnumerable()
        where !(row["eCode"].ToString().Contains("OP"))
        select DataRow(row["time"], row["value"], 
            row["size"], row["condition"], 
            row["eCode"]))
         .CopyToDataTable().DefaultView;
1

1 Answer 1

2

Without knowing your specific application, you might try something like this:

//where dt is your DataTable...
var source = MV.Data;
var newRows = source.Where(d => d.eCode.ToString().Contains("OP"))
                    .Select(d => dt.Rows.Add(d.time, d.value, d.size, d.condition, d.eCode));

I write most of my linq like this as I find the lambdas easier to read. Note that DataTables accepts a list of parameters as an input; no need to construct a DataRow first. The first Where clause checks for your eCode, and select adds the row to your DataTable AND returns it to newRows in case you still need them. If you don't need them, you can either iterate through using ForEach or, if there are few enough rows, do this:

//where dt is your DataTable...
var source = MV.Data;
source.Where(d => d.eCode.ToString().Contains("OP"))
      .ToList() //copies everything into memory
      .Foreach(d => dt.Rows.Add(d.time, d.value, d.size, d.condition, d.eCode));

This approach just incorporates an inline Foreach iteration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.