Jan
Jan

Reputation: 2168

C#: only one typecast in linq?

I have a gridview and each row displays one instance of MyCustomType. The instance itself is stored in the Tag property of DataGridViewRow. Now I want to use linq to select certain rows, based on multiple criteria. This looks like this:

var rows = grid_series.Rows
    .Cast<DataGridViewRow>()
    .Where(x => ((MyCustomType)x).myProperty != string.Empty)
    .Where(x => ((MyCustomType)x).myOtherProperty < 42);

But I really want to avoid to cast the Tag-object in every single where statement. Is there a way to cast the object only once and use repeatedly? I thought about using a select statement first. Then I do have to apply the cast only once, but then I'd have to "re-convert" each result back to DataGridViewRow which I don't think is possible.

Upvotes: 1

Views: 207

Answers (1)

nemesv
nemesv

Reputation: 139818

What about selecting the Tag and do another Cast (or OfType<> of not all the rows contains MyCustomType) afterwards:

var rows = grid_series.Rows
    .Cast<DataGridViewRow>().Select(r => r.Tag).Cast<MyCustomType>()
    .Where(x => x.myProperty != string.Empty)
    .Where(x => x.myOtherProperty < 42);

If you want IEnumerable<DataGridViewRow> you you can try:

var rows = grid_series.Rows
    .Cast<DataGridViewRow>()
    .Select(r => new { MyType = (MyCustomType)r.Tag, Row = r })
    .Where(x => x.MyType.myProperty != string.Empty)
    .Where(x => x.MyType.myOtherProperty < 42)
    .Select(x => x.Row);

Upvotes: 3

Related Questions