有条件转让C#VAR:优雅,因为它得到? [英] Conditionally assign C# var: As elegant as it gets?
问题描述
据我所知,C#关键字的 VAR 的意味在编译时的类型,因此需要在同一个地方申报和分配,使得下面的构造非法的:
VAR的东西;
如果(情况):
{
的东西= 1;
}
,否则
{
的东西= 0;
}
尽管C#编译器可能主要确定在当前范围内产生的所有作业在同类型的,它(目前)没有,因此产生一个编译时错误。
在使用的 VAR 的使用LINQ,我有时会想初始化我的结果变量略有不同取决于程序的条件。我已经找到了一种方法是使用?:运算符,如:
VAR参与者=(电子邮件== NULL
(从部分db.Participant
,其中part.SequenceNumber == seqNr
选择部分)
:
(从部分db.Participant
,其中一部分.EmailAddress ==电子邮件
选择部分));
这工作得很好,如果我只是有两个可能的任务,但如果有多个可能很快就会变得不实用分配。
是否有一个更优雅的方式呢?
<$ C:>您可以使用。凡(...)
$ C> VAR参与者=电子邮件== NULL
? db.Participant.Where(P => p.SequenceNumber == seqNr)
:db.Participant.Where(P => p.EmailAddress ==电子邮件);
但我个人根本不会使用 VAR
在这里 - 它不会扩展到超过2,但是这是一个典型的搜索的格局。我可能是:
的IQueryable<部分>查询= db.Participant;
如果(电子邮件!= NULL)查询= query.Where(P => p.EmailAddress ==电子邮件);
如果(seqNr!= NULL)查询= query.Where(P => p.SequenceNumber == seqNr);
...
//消耗查询
这允许多个条件为(在这种情况下,与),用于更具体的查询组成。你也可以做OR,但它是稍微复杂一些(除非你使用的毗连
/ 联盟
,这是凌乱)。
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).
这篇关于有条件转让C#VAR:优雅,因为它得到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!