保存 "If statement" c# 的输出
Saving output from "If statement" c#
我有一个条件:
List<HWSRunSession> session = new List<HWSRunSession>();
foreach (var item in fileInfo)
{
if(_db.HWSRunSessions.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays) == null) {
bla bla...
}
}
但我想使用“out”关键字将我在条件中检索到的列表保存到我的变量 session
中。有点像:
List<HWSRunSession> session = new List<HWSRunSession>();
foreach (var item in fileInfo)
{
if(_db.HWSRunSessions.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays), out session == null) {
}
}
这可能吗?如果可能的话怎么办?
最可读和可维护的解决方案是将结果存储在一个变量中,然后在条件下测试这个变量:
var session = _db.HWSRunSessions
.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays)
.FirstOrDefault();
if(session == null)
{
// session is null
}
else
{
// do something with session
}
如果您绝对必须在表达式中赋值一个变量,这是可能的。但它使代码更难阅读,更容易遗漏错误:
Session session = null;
if ((session = _db.HWSRunSessions
.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays)
.FirstOrDefault()) == null)
{
// session is null
}
else
{
// do something with session
}
我有一个条件:
List<HWSRunSession> session = new List<HWSRunSession>();
foreach (var item in fileInfo)
{
if(_db.HWSRunSessions.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays) == null) {
bla bla...
}
}
但我想使用“out”关键字将我在条件中检索到的列表保存到我的变量 session
中。有点像:
List<HWSRunSession> session = new List<HWSRunSession>();
foreach (var item in fileInfo)
{
if(_db.HWSRunSessions.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays), out session == null) {
}
}
这可能吗?如果可能的话怎么办?
最可读和可维护的解决方案是将结果存储在一个变量中,然后在条件下测试这个变量:
var session = _db.HWSRunSessions
.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays)
.FirstOrDefault();
if(session == null)
{
// session is null
}
else
{
// do something with session
}
如果您绝对必须在表达式中赋值一个变量,这是可能的。但它使代码更难阅读,更容易遗漏错误:
Session session = null;
if ((session = _db.HWSRunSessions
.Where((x) => x.TransferredZipName == item.Name
&& DateTime.Now.Subtract(x.AddedDate).TotalDays >= _ExpirationDays)
.FirstOrDefault()) == null)
{
// session is null
}
else
{
// do something with session
}