在这样的 LINQ to 实体表达式中:
var vote = (from vote in db.Vote where
vote.Voter.Id == user.Id
select v).FirstOrDefault();
如何添加 DefaultIfEmpty 值,以便在没有投票时获得默认值?
在这样的 LINQ to 实体表达式中:
var vote = (from vote in db.Vote where
vote.Voter.Id == user.Id
select v).FirstOrDefault();
如何添加 DefaultIfEmpty 值,以便在没有投票时获得默认值?
Another approach, if Vote
is a reference type and thus uses null as its default value, would be to use the null coalescing operator:
var vote = (db.Vote
.Where(v => v.Voter.Id == user.Id)
.FirstOrDefault()) ?? defaultVote;
添加您自己的扩展方法。例如:
public static class Extension
{
public static T FirstOrDefault(this IEnumerable<T> sequence, T defaultValue)
{
return sequence.Any() ? sequence.First() : defaultValue;
}
}
在该类的范围内,您可以说:
var vote = (from vote in db.Vote where
vote.Voter.Id == user.Id
select v).FirstOrDefault(yourDefaultValue);
当然,您的方法也可以有一个返回 default(T) 的重载,如果那是您要查找的内容。内置 Extension 类中已经定义了一个 DefaultIfEmpty 扩展方法,所以我在示例中将该方法命名为“FirstOrDefault”,这样看起来更合适。
只需在获取第一个元素之前添加默认值即可。
var vote = db.Vote
.Where(v => v.Voter.Id == user.Id)
.DefaultIfEmpty(defaultVote)
.First();
请注意,您现在可以安全地使用First()
而不是FirstOrDefault()
.
更新
LINQ to Entity does not recognize the DefaultIfEmpty()
extension method. But you can just use the null coalescing operator.
var vote = db.Vote.FirstOrDefault(v => v.Voter.Id == user.Id) ?? defaultVote;
I ended up going for a very simple approach which was recommended by an answer here that was latter erased:
var vote = (from vote in db.Vote
where vote.Voter.Id == user.Id
select v).FirstOrDefault();
if (vote == null) {
vote = new Vote() { .... };
db.AddToVoteSet(vote);
}
For some reason if I turn the resultset into a List, the Defaultifempty() works I don't know if I've inadvertantly crossed over into Linq area.
var results = (from u in rv.tbl_user
.Include("tbl_pics")
.Include("tbl_area")
.Include("tbl_province")
.ToList()
where u.tbl_province.idtbl_Province == prov
select new { u.firstName, u.cellNumber, u.tbl_area.Area, u.ID, u.tbl_province.Province_desc,
pic = (from p3 in u.tbl_pics
where p3.tbl_user.ID == u.ID
select p3.pic_path).DefaultIfEmpty("defaultpic.jpg").First()
}).ToList();