本文整理汇总了C#中IQueryable.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# IQueryable.FirstOrDefault方法的具体用法?C# IQueryable.FirstOrDefault怎么用?C# IQueryable.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IQueryable
的用法示例。
在下文中一共展示了IQueryable.FirstOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ClassLibServiceUnitTests
public ClassLibServiceUnitTests()
{
Service.ClassLib.pt12lolConfigurator.ConfigureAutoMapper();
fakeUserProfiles = new[]
{
new UserProfile { UserId = 1, UserName = "pt12lol" },
new UserProfile { UserId = 2, UserName = "user" },
new UserProfile { UserId = 3, UserName = "test" }
}.AsQueryable();
fakeMemberships = new[]
{
new webpages_Membership { UserId = 1, Password = "hashedPass1", PasswordSalt = "secretSalt1" },
new webpages_Membership { UserId = 2, Password = "hashedPass2", PasswordSalt = "secretSalt2" },
new webpages_Membership { UserId = 3, Password = "hashedPass3", PasswordSalt = "secretSalt3" }
}.AsQueryable();
var userProfileRepositoryMock = new Mock<IEntitiesRepository<UserProfile>>();
var membershipRepositoryMock = new Mock<IEntitiesRepository<webpages_Membership>>();
userProfileRepositoryMock.Setup(r => r.Get(It.IsAny<Expression<Func<UserProfile, bool>>>()))
.Returns<Expression<Func<UserProfile, bool>>>(pred => fakeUserProfiles.Where(pred));
membershipRepositoryMock.Setup(r => r.Get(It.IsAny<int>()))
.Returns<int>(id => fakeMemberships.FirstOrDefault(m => m.UserId == id));
membershipRepositoryMock.Setup(x => x.Get(It.IsAny<Expression<Func<webpages_Membership, bool>>>()))
.Returns<Expression<Func<webpages_Membership, bool>>>(pred => fakeMemberships.Where(pred));
_userProfileService = new UserProfileDbService(() => userProfileRepositoryMock.Object, () => membershipRepositoryMock.Object);
}
示例2: CompareAndPrepareProfile
private void CompareAndPrepareProfile(string profileName, string profileValue, string userName, string logoUrl, IQueryable<UserSiteProfile> siteProfiles, string prefix)
{
var siteProfile = siteProfiles.FirstOrDefault(x => x.Name == profileName);
if (siteProfile != null && string.IsNullOrWhiteSpace(profileValue))
{
profileRepo.DeleteOnCommit(siteProfile);
}
if (siteProfile == null && !string.IsNullOrWhiteSpace(profileValue))
{
var newSiteProfile = new UserSiteProfile();
newSiteProfile.Username = userName;
newSiteProfile.Name = profileName;
newSiteProfile.Url = prefix + profileValue;
newSiteProfile.Image = logoUrl;
profileRepo.InsertOnCommit(newSiteProfile);
}
if (siteProfile != null && !string.IsNullOrWhiteSpace(profileValue))
{
siteProfile.Url = prefix + profileValue;
siteProfile.Image = logoUrl;
}
}
示例3: WriteToExcelFile
public void WriteToExcelFile(IQueryable<History> histories)
{
var mySheet = (Excel.Worksheet) _myBook.Sheets[1];
var currenRow = 2;
var lastEmployeeId = histories.FirstOrDefault().Employee.EmployeeID;
foreach (var history in histories) {
if (currenRow == 2)
{
mySheet.Cells[currenRow, _employeeNameColumn] = history.Employee.Name;
mySheet.Cells[currenRow, _numberOfPaymentColumn] = history.Employee.Cycle;
}
else if (lastEmployeeId != history.Employee.EmployeeID)
{
currenRow++;
lastEmployeeId = history.Employee.EmployeeID;
mySheet.Cells[currenRow, _employeeNameColumn] = history.Employee.Name;
mySheet.Cells[currenRow, _numberOfPaymentColumn] = history.Employee.Cycle;
}
string debug = history.Dated.ToString("dd-MMM-yy");
mySheet.Cells[currenRow, _dateColumn] = debug;
mySheet.Cells[currenRow, _amountOfPaymentColumn] = history.Amount;
currenRow++;
}
}
示例4: CheckUser
public static bool CheckUser(MembershipAccount user, IQueryable<MembershipRole> roles, IQueryable<MembershipPermission> permissionsQuery, string[] currentPermissions)
{
List<MembershipPermission> allPermissions = permissionsQuery.ToList();
List<string> permissions = new List<string>();
if (user == null)
{
var role = roles.FirstOrDefault(x => x.RoleName == DefaultRoles.Anonymous);
if (role != null)
permissions = role.Permissions;
}
else
{
permissions = user
.Roles
.SelectMany(x => x.Permissions)
.ToList();
permissions.AddRange(user.Permissions);
}
var currentPermissionEntities = allPermissions.Where(x => currentPermissions.Any(y => y == x.Name)).ToList();
if (permissions.Any(x => currentPermissionEntities.FirstOrDefault(y => y.Name == x) != null))
{
return true;
}
else
{
return false;
}
}
示例5: SiteModel
public SiteModel(SiteContext context, string contentId, string productId, bool notFound = false)
{
Contents = context.Contents;
Title = "Студия Евгения Миллера";
var minSortorder = Contents.Min(c => c.SortOrder);
foreach (var content in Contents.Where(content => content.SortOrder == minSortorder))
{
content.IsHomepage = true;
break;
}
if (productId != null)
{
Product = context.Products.FirstOrDefault(p => p.Name == productId);
if (Product == null)
{
throw new HttpException(404, "page not found");
}
Content = Product.Content;
}
else if (contentId == "")
{
//Content = Contents.First(c => c.IsHomepage==true);
Content = Contents.First(content => content.SortOrder == minSortorder);
}
else
{
Content = Contents.FirstOrDefault(c => c.Name == contentId);
}
if (Content == null)
{
throw new HttpException(404, "page not found");
}
var contentName = Content.Name;
Menu = new List<Helpers.MenuItem>();
foreach (var c in Contents)
{
Menu.Add(new Helpers.MenuItem
{
ContentId = c.Id,
ContentName = c.Name,
Current = !notFound && ((c.Name == contentId || contentId == "" && c.IsHomepage) && Product == null),
Selected = !notFound && c.Name == contentName,
SortOrder = c.SortOrder,
Title = c.Title
});
}
Title += " » " + Content.Title;
SeoDescription = Content.SeoDescription;
SeoKeywords = Content.SeoKeywords;
}
示例6: Init
private static void Init()
{
posts = (new List<Post>() {
new Post("title", "content", "#", "J", DateTime.UtcNow),
new Post("title 2", "content z", "#", "M", DateTime.UtcNow.AddDays(2)){PostId = 2, Tags = new List<Tag>(){new Tag("aa"),new Tag("bb")}},
new Post("fan roosh", "content k", "#", "F", DateTime.UtcNow.AddDays(-1))
}).AsQueryable();
postRepository = MockRepository.GenerateStub<IPostRepository>();
postRepository.Stub(x => x.RecentPosts(Arg<int>.Is.Anything))
.WhenCalled(x => x.ReturnValue = posts.Where(y => y.PublishDate <= DateTime.UtcNow).Take((int)x.Arguments[0]));
postRepository.Stub(x => x.Find(Arg<long>.Is.Anything))
.WhenCalled(x => x.ReturnValue = posts.FirstOrDefault(y => y.PostId == (long)x.Arguments[0]))
.Return(new Post());
}
示例7: SiteModel
public SiteModel(SiteContext context, string contentId, int? productId = null)
{
Contents = context.Content;
Title = "Майкаджексон";
var minSortorder = Contents.Min(c => c.SortOrder);
foreach (var content in Contents.Where(content => content.SortOrder == minSortorder))
{
content.IsHomepage = true;
break;
}
// в случае заходи на страницу продукта
if (contentId == null)
{
Product = context.Product.First(p => p.Id == productId);
Content = Product.Content;
}
else if (contentId == "")
{
//Content = Contents.First(c => c.IsHomepage==true);
Content = Contents.First(content => content.SortOrder == minSortorder);
}
else
{
Content = Contents.FirstOrDefault(c => c.Name == contentId);
}
Menu = new List<Helpers.MenuItem>();
foreach (var c in Contents)
{
Menu.Add(new Helpers.MenuItem
{
ContentId = c.Id,
ContentName = c.Name,
Current = c.Name == contentId || contentId == "" && c.IsHomepage,
Selected = c.Name == Content.Name,
SortOrder = c.SortOrder,
Title = c.MenuTitle,
ContentType = (ContentType)c.ContentType
});
}
SeoDescription = Content.SeoDescription;
SeoKeywords = Content.SeoKeywords;
}
示例8: GetPrimaryCustomerAddress
internal static CustomerAddress GetPrimaryCustomerAddress(IQueryable<CustomerAddress> customerAddresses, AddressType addressType)
{
if (!customerAddresses.Any())
{
return null;
}
CustomerAddress customerBillingAddress = customerAddresses.FirstOrDefault(ca => ca.AddressType == addressType && ca.IsPrimary);
if (customerBillingAddress == null)
{
// There is no primary address. Get the most recent address.
customerBillingAddress = customerAddresses.Where(ca => ca.AddressType == AddressType.Billing).OrderByDescending(ca => ca.LastModified).First();
}
return customerBillingAddress;
}
示例9: MakeCostDetail
public CostDetail MakeCostDetail(IQueryable<TaskExecutor> tskExecs, IQueryable<Article> articles, string codTaskExecutor = "")
{
CostDetail cv = null;
ProductPart productPart = null;
#region Materiale
if (this.CodProductPartPrintableArticle != null)
{
var productPartPrintableArticle = this.ProductPartsPrintableArticle;
productPart = this.ProductPartsPrintableArticle.ProductPart;
var task = productPart.ProductPartTasks.FirstOrDefault(x => x.OptionTypeOfTask.CodTypeOfTask.Contains("STAMPA"));
//il tipo di materiale dipende dalla stampa o dal tipo di prodotto?
//productPartPrintabelArticles = productPart.ProductPartPrintableArticles;
}
#endregion
#region Impianto
if (this.CodProductPartImplantTask != null)
{
productPart = this.ProductPartImplantTask.ProductPart;
// var task = productPart.ProductPartTasks.FirstOrDefault(x => x.OptionTypeOfTask.CodTypeOfTask.Contains("STAMPA"));
var task = productPart.ProductPartTasks.FirstOrDefault(x => x.CodProductPartTask == this.CodProductPartImplantTask);
}
#endregion
#region Lavorazione
//E' una lavorazione!!!!
String codTypeOfTask = String.Empty;
if (this.CodProductPartTask != null)
{
codTypeOfTask = this.ProductPartTask.OptionTypeOfTask.CodTypeOfTask;
productPart = this.ProductPartTask.ProductPart;
}
#region tavolo di controllo rotolo
if (codTypeOfTask == "TAVOLOCONTROLLO")
{
Console.WriteLine("Tavolo di controllo");
String codParte = String.Empty;
tskExecs = TaskExecutor.FilterByTask(tskExecs, codTypeOfTask);
if (tskExecs.Count() > 0)
{
switch (tskExecs.FirstOrDefault().TypeOfExecutor)
{
case TaskExecutor.ExecutorType.ControlTableRoll:
cv = new ControlTableCostDetail();
cv.TaskCost = this;
cv.InitCostDetail(tskExecs, articles);
cv.SetTaskexecutor(tskExecs, codTaskExecutor);
break;
default:
break;
}
cv.ProductPart = productPart;
cv.CodCost = this.CodCost;
cv.CodCostDetail = this.CodCost;
}
}
#endregion
#region serigrafia rotolo!!! ripasso!!!
if (codTypeOfTask == "SERIGRAFIAROTOLO" || codTypeOfTask == "STAMPAACALDOROTOLO")
{
Console.WriteLine("Serigrafia rotolo");
String codParte = String.Empty;
tskExecs = TaskExecutor.FilterByTask(tskExecs, codTypeOfTask);
if (tskExecs.Count() > 0)
{
switch (tskExecs.FirstOrDefault().TypeOfExecutor)
{
case TaskExecutor.ExecutorType.FlatRoll:
cv = new RepassRollCostDetail();
cv.TaskCost = this;
cv.InitCostDetail(tskExecs, articles);
cv.SetTaskexecutor(tskExecs, codTaskExecutor);
break;
//.........这里部分代码省略.........
示例10: LookupByType
private static TypeRef LookupByType(IReadOnlyZetboxContext ctx, IQueryable<TypeRef> source, Type t)
{
// TODO: think about and implement naked types (i.e. without arguments)
if (t.IsGenericTypeDefinition) throw new ArgumentOutOfRangeException("t");
if (t.IsGenericType)
{
string fullName = t.GetGenericTypeDefinition().FullName;
var args = t.GetGenericArguments().Select(arg => arg.ToRef(ctx)).ToArray();
var argsCount = args.Count();
foreach (var tRef in source.Where(tRef
=> tRef.Assembly.Name == t.Assembly.FullName
&& tRef.FullName == fullName
&& tRef.GenericArguments.Count == argsCount))
{
bool equal = true;
for (int i = 0; i < tRef.GenericArguments.Count; i++)
{
equal &= args[i] == tRef.GenericArguments[i];
if (!equal)
break;
}
if (equal)
return tRef;
}
return null;
}
else
{
// ToList: Workaround Case 1212
return source.FirstOrDefault(tRef
=> tRef.Assembly.Name == t.Assembly.FullName
&& tRef.FullName == t.FullName
&& tRef.GenericArguments.Count == 0);
}
}
示例11: GetGroupByDate
public Group GetGroupByDate(IQueryable<Group> Groups, int GroupId, DateTime Date)
{
var r = Groups.FirstOrDefault(g => g.GroupId == GroupId);
if (r != null && r.ParentGroup != null)
{
if (r.CreatedDate < Date)
{
return r;
}
else
{
return GetGroupByDate(Groups, r.ParentGroup.GroupId, Date); // Get the parent, if existing..
}
}
else
return r; // Return the matching record
}
示例12: AddOrResendInvitation
private void AddOrResendInvitation(string inviteeEmail, Invitation i, IQueryable<Invitation> prevSentInvitations)
{
if (prevSentInvitations.Any(o => o.StatusValue == (int) InvitationStatus.Blocked))
throw new Exception("This user blocked invitations from you.");
//check already existing invitation to this project
var prevSentToThisProject = prevSentInvitations.FirstOrDefault(o => o.ProjectId == i.ProjectId);
if (prevSentToThisProject != null)
{
switch (prevSentToThisProject.Status)
{
case InvitationStatus.Sent:
throw new Exception("You have already sent invitation to this user.");
break;
case InvitationStatus.Accepted:
throw new Exception("This user is already in your team.");
break;
case InvitationStatus.Declined:
prevSentToThisProject.LastSentDate = DateTime.UtcNow;
//resend invitation email again
MessageService.SendEmail(inviteeEmail, "Invitation to project", "InviteToProject",
new EmailDTO<Invitation>(prevSentToThisProject));
Database.ObjectContext.ApplyCurrentValues("Invitations", prevSentToThisProject);
Database.SaveChanges();
return;
break;
}
}
i.Project = Database.Projects.FirstOrDefault(p => p.Id == i.ProjectId);
Database.Invitations.Add(i);
Database.SaveChanges();
//sent email
MessageService.SendEmail(inviteeEmail, "Invitation to project", "InviteToProject",
new EmailDTO<Invitation>(i));
}
示例13: UpdateTransactions
private void UpdateTransactions(string Iuser, IQueryable<CurrencyLookupItem> aimsCurrencies, IQueryable<AidCategoryLookupItem> aimsAidCategories, string defaultfinancetype, tblProjectInfo p, iatiactivity MatchedProject)
{
#region Commitments
if (MatchedProject.IsCommitmentIncluded)
{
foreach (var trn in MatchedProject.CommitmentsThisDPOnly)
{
var aimsCommitment = new tblProjectFundingCommitment();
p.tblProjectFundingCommitments.Add(aimsCommitment);
aimsCommitment.IDate = DateTime.Now;
aimsCommitment.IUser = Iuser;
aimsCommitment.IsCommitmentTrustFund = false;
//ToDo for co-finance projects it may be different
aimsCommitment.FundSourceId = MatchedProject.AimsFundSourceId;
aimsCommitment.CommitmentAgreementSignDate = trn.transactiondate?.isodate.ToSqlDateTimeNull();
var aimsCurrency = aimsCurrencies.FirstOrDefault(f => f.IATICode == trn.value.currency);
aimsCommitment.CommitmentMaidCurrencyId = aimsCurrency == null ? 1 : aimsCurrency.Id;
aimsCommitment.CommittedAmount = trn.value.Value;
aimsCommitment.CommitmentEffectiveDate = trn.value?.BBexchangeRateDate;
aimsCommitment.ExchangeRateToUSD = trn.value?.BBexchangeRateUSD ?? default(decimal);
aimsCommitment.CommittedAmountInUSD = trn.value?.ValueInUSD;
aimsCommitment.ExchangeRateToBDT = trn.value?.BBexchangeRateBDT ?? default(decimal);
aimsCommitment.CommittedAmountInBDT = trn.value?.ValueInBDT;
aimsCommitment.Remarks = MatchedProject.IsDataSourceAIMS ? trn.description?.narrative.n(0).Value : "Importerd From IATI: " + trn.description?.narrative.n(0).Value;
aimsCommitment.VerificationRemarks = "Importerd From IATI: ";
//AidCategory
if (trn.financetype != null && trn.financetype.code.Length > 1)
defaultfinancetype = trn.financetype.code.StartsWith("4") ? "400" : "100";
var aimsAidCategory = aimsAidCategories.FirstOrDefault(f => f.IATICode == defaultfinancetype);
aimsCommitment.AidCategoryId = aimsAidCategory == null ? 1 : aimsAidCategory.Id;
}
}
#endregion
#region PlannedDisbursements
if (MatchedProject.IsPlannedDisbursmentIncluded)
{
foreach (var trn in MatchedProject.PlannedDisbursments)
{
var aimsPlanDisbursment = new tblProjectFundingPlannedDisbursement();
p.tblProjectFundingPlannedDisbursements.Add(aimsPlanDisbursment);
aimsPlanDisbursment.IDate = DateTime.Now;
aimsPlanDisbursment.IUser = Iuser;
aimsPlanDisbursment.IsPlannedDisbursementTrustFund = false;
//ToDo for co-finance projects it may be different
aimsPlanDisbursment.FundSourceId = MatchedProject.AimsFundSourceId;
aimsPlanDisbursment.PlannedDisbursementPeriodFromDate = trn.periodstart?.isodate.ToSqlDateTimeNull();
aimsPlanDisbursment.PlannedDisbursementPeriodToDate = trn.periodend?.isodate.ToSqlDateTimeNull();
var aimsCurrency = aimsCurrencies.FirstOrDefault(f => f.IATICode == trn.value.currency);
aimsPlanDisbursment.PlannedDisbursementCurrencyId = aimsCurrency == null ? 1 : aimsCurrency.Id;
aimsPlanDisbursment.PlannedDisburseAmount = trn.value.Value;
aimsPlanDisbursment.PlannedDisburseExchangeRateToUSD = trn.value?.BBexchangeRateUSD ?? default(decimal);
aimsPlanDisbursment.PlannedDisburseAmountInUSD = trn.value?.ValueInUSD;
aimsPlanDisbursment.PlannedDisburseExchangeRateToBDT = trn.value?.BBexchangeRateBDT ?? default(decimal);
aimsPlanDisbursment.PlannedDisburseAmountInBDT = trn.value?.ValueInBDT;
//aimsPlanDisbursment.VerificationRemarks = project.IsDataSourceAIMS ? trn.description?.narrative.n(0).Value : "Importerd From IATI: " + trn.description?.narrative.n(0).Value;
aimsPlanDisbursment.VerificationRemarks = "Importerd From IATI: ";
//AidCategory
var aimsAidCategory = aimsAidCategories.FirstOrDefault(f => f.IATICode.StartsWith(defaultfinancetype));
aimsPlanDisbursment.AidCategoryId = aimsAidCategory == null ? 1 : aimsAidCategory.Id;
}
}
#endregion
#region Disbursements
if (MatchedProject.IsDisbursmentIncluded)
{
foreach (var trn in MatchedProject.DisbursmentsThisDPOnly)
{
var aimsDisbursment = new tblProjectFundingActualDisbursement();
p.tblProjectFundingActualDisbursements.Add(aimsDisbursment);
aimsDisbursment.IDate = DateTime.Now;
aimsDisbursment.IUser = Iuser;
aimsDisbursment.IsDisbursedTrustFund = false;
//.........这里部分代码省略.........
示例14: InitCostDetail
public override void InitCostDetail(IQueryable<TaskExecutor> tskExec, IQueryable<Article> articles)
{
if (!justInited)
{
base.InitCostDetail(tskExec, articles);
_articles = articles.ToList().AsQueryable();
String codTypeOfTask = String.Empty;
//Console.WriteLine(ProductPart); //= TaskCost.ProductPartTask.ProductPart;
codTypeOfTask = TaskCost.ProductPartTask.OptionTypeOfTask.CodTypeOfTask;
tskExec = TaskExecutor.FilterByTask(tskExec, codTypeOfTask);
TaskExecutors = tskExec.ToList();
ICollection<ProductPartsPrintableArticle> productPartPrintabelArticles = new List<ProductPartsPrintableArticle>();
productPartPrintabelArticles = TaskCost.ProductPartTask.ProductPart.ProductPartPrintableArticles;
#region Format
List<string> formats = new List<string>();
var widthList = new List<Nullable<double>>();
//
//voglio sapere quali sono i formati degli articoli ma gli articoli che posso stampare dipendono dal tipo di macchina!!!!
foreach (var item in productPartPrintabelArticles)
{
widthList = articles.OfType<RollPrintableArticle>()
.Where(x => x.TypeOfMaterial == item.TypeOfMaterial &&
x.Color == item.Color &&
x.Adhesive == item.Adhesive &&
x.Weight == item.Weight &&
x.NameOfMaterial == item.NameOfMaterial)
.Select(x => x.Width).ToList();
}
//FLAT
//***********************************************
foreach (var width in widthList)
{
if (BuyingWidths == null) BuyingWidths = new List<double>();
BuyingWidths.Add(width ?? 0);
}
//FLEXO
//**********************************************
var tskCurrent = tskExec.FirstOrDefault(x => x.CodTaskExecutor == CodTaskExecutorSelected);
if (tskCurrent == null)
{
tskCurrent = tskExec.FirstOrDefault();
}
var zList = new List<string>();
foreach (var item in tskCurrent.TaskExecutorCylinders)
{
if (tskCurrent.TypeOfExecutor == TaskExecutor.ExecutorType.Flexo)
{
zList.Add(
((Flexo)tskCurrent).GetCmFromZ(item.Z ?? 0).ToString());
}
else
{
zList.Add((Convert.ToDouble(item.Z) / 8 * 2.54).ToString());
}
}
//combino i width con gli Z
foreach (var width in widthList.Where(x => x != 0))
{
foreach (var z in zList)
{
var x = (width ?? 0).ToString("0.00", Thread.CurrentThread.CurrentUICulture) + "x" + z;
if (!formats.Contains(x))
formats.Add((width ?? 0).ToString("0.00", Thread.CurrentThread.CurrentUICulture) + "x" + z);
}
}
BuyingFormats = formats;
//**********************************************
#endregion
}
}
示例15: GetMood
public Moods.type GetMood(IQueryable<DetectionResult> entities)
{
var attention = entities.FirstOrDefault(x => x.TypeOfFrequency == 0);
var meditation = entities.FirstOrDefault(x => x.TypeOfFrequency == 1);
attention = attention ?? new DetectionResult();
meditation = meditation ?? new DetectionResult();
if (attention.Average > 50 && meditation.Average > 50)
return Moods.type.CONFUSED;
else if (attention.Average < 50 && meditation.Average > 50)
return Moods.type.CONTEMPLATIVE;
else if (attention.Average > 50 && meditation.Average < 50)
return Moods.type.FOCUSED;
else
return Moods.type.THOUGHTFUL;
}