views:

100

answers:

1

I'm trying to see if there is a way to build a Linq statement that would choose based off available attributes in an element what the result would be, although not all attributes are always available.

For example, this would be a 'standard' element:

<box left="2" right="2" />

However, this is also perfectly valid:

<box left="3" />

And this:

<box right="1.4" />

What I'd like to do is have a Linq statement that says "if left and right both exist, add them and divide by 2. if only left exists, use that value. if only right exists, use that value.". I know this can be done via a series of convoluted If/Then statements, but I'm trying to see if this can be done in Linq.

I've tried a few things, but am having problems with the return value - how to return the one that is true. For example, the following returns values, but not necessarily the one that is true:

dim center = from e in <box> Where e.@left IsNot Nothing _
AndAlso e.@right IsNot Nothing _
let g = ((CInt(e.@left)+CInt(e.@right)) /2) _
Or _
e.@left IsNot Nothing AndAlso e.@right Is Nothing _
let k = CInt(e.@left)

I've tried using select statements, but it's not exactly working. Any thoughts on how this can be done?

+2  A: 

Use If expression:

Dim center = From e In <box> _
             Where If(e.@left IsNot Nothing AndAlso e.@right IsNot Nothing, _
                      (CInt(e.@left) + CInt(e.@right)) / 2, _
                      If (e.@left IsNot Nothing, _
                          CInt(e.@left), _
                          CInt(e.@right)))
Pavel Minaev
that is perfect pavel, i just changed the "where" to "select" and it worked like a charm. thank you!
Otaku