English 中文(简体)
Conditionally assign C# var: As elegant as it gets?
原标题:

I understand that the C# keyword var implies the type at compile time and therefore requires the declaration and assignment in the same place, making the following construct illegal:

var something;

if (condition)
{
    something=1;
}
else
{
    something = 0;
}

Even though the C# compiler could principally determine that all assignments in the current scope result in the same type, it (presently) does not and therefore generates a compile time error.

In using var with LINQ, I sometimes want to initialize my result variable slightly differently depending on program conditions. The approach I have found is to use the ?: operator, as in:

var participants = (email == null ?
                   (from part in db.Participant
                    where part.SequenceNumber == seqNr
                    select part)
                   :
                   (from part in db.Participant
                    where part.EmailAddress == email
                    select part));

That works well enough if I just have two possible assignments, but quickly becomes unwieldy if there are multiple possible assignments.

Is there a more elegant approach to this?

最佳回答

You could use .Where(...) rather than query syntax:

var participants = email == null
    ? db.Participant.Where(p => p.SequenceNumber == seqNr)
    : db.Participant.Where(p => p.EmailAddress == email);

but personally I simply wouldn t use var here - it doesn t scale beyond 2, but this is a classic "search" pattern. I might use:

IQueryable<Part> query = db.Participant;
if(email != null) query = query.Where(p => p.EmailAddress == email);
if(seqNr != null) query = query.Where(p => p.SequenceNumber == seqNr);
...
// consume query

This allows multiple conditions to be composed (in this case "AND") for a more specific query. You can also do "OR" but it is slightly more complex (unless you use Concat/Union, which is messy).

问题回答

This strikes me as a workaround for a database design problem.

I think the more elegant approach would be factoring the code in such a way as to have one method that handles each different program condition.

I.e.:

if (email == null) {
    DoStuffWhenEmailIsNull();
}
else {
    DoStuffWhenEmailIsNotNull();
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签