0

I currently have the following code:

dataSource.Where(row => row.Value == 1)
          .Select(row => {row["Text"] = translatedText; return row;})
          .Single();

So my goal is to select the DataRow with "Value=1" and at the same time set the value in the "Text"-column to some other value (in my case a string-variable transalatedText).

This already works fine with the method chain mentioned above but I generally prefer the LINQ syntax. Is there a possibility to translate this method chain to LINQ?

My problem is that I do not know how to translate the function in the Select-method to LINQ-format. I dont want to create a new DataRow but want to really edit the selected one. (So I don't want to use from x in y where z select new DataRow(...) but to really edit my x if possible)

Thanks!

1 Answer 1

2

Is there a possibility to translate this method chain to LINQ?

(By "to LINQ" I believe you mean "to query expression syntax".)

Not directly, no. Effectively, you can only convert expression-bodied lambda expressions into query syntax. There's a good reason for that: LINQ is designed not to have side effects, whereas your "query" does have side-effects.

I would personally write your code like this instead:

var row = DataSource.Single(row => row.Value == 1);
row["Text"] = translatedText;

That neatly separates the querying from the side-effect. If you really, really want to use query expression syntax, you could write:

var query = (from row in DataSource
             where row.Value == 1)
             select HorribleMutatingMethod(row)).Single();
...

private DataRow HorribleMutatingMethod(DataRow row)
{
    row["Text"] = translatedText;
    return row;
}

... but please don't.

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

1 Comment

Yeah, i mean "query expression syntax", thanks for that. Your solution works fine for my case, but I wanted to keep the question as "general" as possible (eg. a renaming with Where(row => new []{1, 2, 3}.Contains(row.Value))

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.