当前位置: 首页>>代码示例>>C#>>正文


C# IQueryable.Where方法代码示例

本文整理汇总了C#中IQueryable.Where方法的典型用法代码示例。如果您正苦于以下问题:C# IQueryable.Where方法的具体用法?C# IQueryable.Where怎么用?C# IQueryable.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IQueryable的用法示例。


在下文中一共展示了IQueryable.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FilterCustomers

        private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
        {
            switch (rule.field)
            {
                case "CustomerId":
                    return customers.Where(c => c.CustomerId == rule.data);

                case "Name":
                    return customers.Where(c => c.Fullname.ToLower().Contains(rule.data.ToLower()));

                case "Company":
                    return customers.Where(c => c.Company.ToLower().Contains(rule.data.ToLower()));

                case "EmailAddress":
                    return customers.Where(c => c.EmailAddress.ToLower().Contains(rule.data.ToLower()));

                case "Last Modified":
                    DateTime dateResult;
                    return !DateTime.TryParse(rule.data, out dateResult) ? customers : customers.Where(c => c.LastModified.Date == dateResult.Date);

                case "Telephone":
                    return customers.Where(c => c.Telephone.ToLower().Contains(rule.data.ToLower()));

                default:
                    return customers;
            }
        }
开发者ID:Janvanderheide,项目名称:MvcJqGrid,代码行数:27,代码来源:Repository.cs

示例2: AddNeededWhereClauses

 private IQueryable<SubscriptionPost> AddNeededWhereClauses(string query,
     IQueryable<SubscriptionPost> subscriptionPosts)
 {
     foreach (var whereClause in GetWhereClausesFromQuery(query))
     {
         switch (whereClause.PropertyName)
         {
             case PropertyName.Author:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Authors.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Content:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Content.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Categories:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Categories.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Feed:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Subscription.Title.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Title:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Title.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
         }
     }
     return subscriptionPosts;
 }
开发者ID:nakioman,项目名称:bralek,代码行数:31,代码来源:FeedItemsService.cs

示例3: InsertContinuousIntoSequence

        /// <summary>
        /// Вставляет изменяемую со временем величину в последовательность, выполняя необходимые преобразования. !!! не вызывает ExecuteDynamicInsert
        /// </summary>
        /// <param name="Inserted">Вставляемая запись</param>
        /// <param name="History">Последовательность изменений данного параметра</param>
        private void InsertContinuousIntoSequence(IContinuous Inserted, IQueryable<IContinuous> History)
        {
            if (Inserted.EndDate != null && History.Any(p => p.StartDate > Inserted.StartDate && p.EndDate < Inserted.EndDate))
                throw new Exception("Добавляемой значение перекрывает уже имеющееся в базе, что нарушает логику построения базы и, скорее всего, свидетельствует об ошибке.");

            var Previus = History
                .Where(p => p.StartDate < Inserted.StartDate)
                .OrderByDescending(p => p.StartDate)
                .FirstOrDefault();

            var Next = History
                .Where(p => p.StartDate > (Inserted.EndDate ?? Inserted.StartDate))
                .OrderBy(p => p.StartDate)
                .FirstOrDefault();

            if (Next != null)
            {
                if (Inserted.EndDate == null) Inserted.EndDate = Next.StartDate;
                else throw new NotImplementedException(String.Format("Указана конечная дата действия свойства, и существует свойство, с датой начала, позже даты конца действия этого свойства. Такой функционал не реализован."));
            }
            if (Previus != null && (Previus.EndDate == null || Previus.EndDate > Inserted.StartDate))
            {
                Previus.EndDate = Inserted.StartDate;
                ExecuteDynamicUpdate(Previus);
            }
        }
开发者ID:NpoSaut,项目名称:LocoBase,代码行数:31,代码来源:LocoDataContext.cs

示例4: ApplyFilter

        public IQueryable<EnhancedStudentInformation> ApplyFilter(IQueryable<EnhancedStudentInformation> query, StudentMetricsProviderQueryOptions providerQueryOptions)
        {
            //If the Staff USI Isn't set, then no-op.
            if (providerQueryOptions.StaffUSI <= 0)
                return query;

            //The only way a Staff member can be associated with a student at LEA is via the Staff Cohort tables.  Only check that one table.
            if (providerQueryOptions.LocalEducationAgencyId.HasUsableValue() && !providerQueryOptions.SchoolId.HasUsableValue())
            {
                var staffStudentCohorts = StaffStudentCohortRepository.GetAll();
                IQueryable<StaffCohort> staffCohort = StaffCohortRepository.GetAll().Where(sc => sc.StaffUSI == providerQueryOptions.StaffUSI);

                return query.Where(si => staffStudentCohorts
                    .SelectMany(ssc => staffCohort.Where(sc => ssc.StaffCohortId == sc.StaffCohortId).Select(sc => ssc))
                    .Any(ssc => ssc.StudentUSI == si.StudentUSI));
            }

            //At the school level, a staff member can be associated by Cohort or by Section.  This view collapses the two.
            var ssa = StaffStudentAssociationRepository.GetAll();
            return query.Where(student => ssa.Any(ms => ms.StudentUSI == student.StudentUSI
                                                        && ms.SchoolId == student.SchoolId
                //This filters on school id, because if a teacher is a teacher at two schools,
                //We need to filter on the Staff Section records only for the current school.
                                                        && ms.SchoolId == providerQueryOptions.SchoolId.GetValueOrDefault()
                                                        && ms.StaffUSI == providerQueryOptions.StaffUSI));
        }
开发者ID:sybrix,项目名称:EdFi-App,代码行数:26,代码来源:StaffUSIFilter.cs

示例5: doSearch

        /// <summary>
        /// Private helper method to perform a new search or maintain a previous search through 
        /// pagination and filter changes
        /// </summary>
        /// <param name="workouts">The base workout query result</param>
        /// <param name="search">The WorkoutSearch object containing the parameters to search</param>
        /// <param name="sortBy">The passed sort string if it exists, else null</param>
        /// <param name="page">The passed page param if it exists, else null</param>
        /// <param name="session">The Session object to get or set variables from/to</param>
        /// <param name="viewBag">The viewBag object to pass the set variables back to the view with</param>
        /// <returns>The searched workouts</returns>
        public static IQueryable<workout> doSearch(IQueryable<workout> workouts, WorkoutSearch search, string sortBy, int? page, HttpSessionStateBase session, dynamic viewBag)
        {
            if (page != null || !String.IsNullOrEmpty(sortBy))
            {
                search = SessionVariableManager.setSearchFromSession(session, search);
            }
            else SessionVariableManager.setSessionFromSearch(session, search);

            if (!String.IsNullOrEmpty(search.name)) workouts = workouts.Where(w => w.name.Contains(search.name));
            if (!String.IsNullOrEmpty(search.category)) workouts = workouts.Where(w => w.category.name.Contains(search.category));
            if (!String.IsNullOrEmpty(search.username)) workouts = workouts.Where(w => w.user.username.Contains(search.username));
            if (!String.IsNullOrEmpty(search.dateAdded))
            {
                string[] dateArrayString = search.dateAdded.Split('-');
                int year = Convert.ToInt16(dateArrayString[0]);
                int month = Convert.ToInt16(dateArrayString[1]);
                int day = Convert.ToInt16(dateArrayString[2]);

                workouts = workouts.Where(w =>
                    w.created_at.Year == year &&
                    w.created_at.Month == month &&
                    w.created_at.Day == day);
            }
            return workouts;
        }
开发者ID:marinaushakova,项目名称:GoFit,代码行数:36,代码来源:WorkoutSortSearch.cs

示例6: FilterCustomers

        private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
        {
            if (rule.field == "CustomerId")
            {
                int result;
                if (!int.TryParse(rule.data, out result))
                    return customers;
                return customers.Where(c => c.CustomerID == Convert.ToInt32(rule.data));

            }
            if (rule.field == "Name")
                return from c in customers
                       where c.FirstName.Contains(rule.data) || c.LastName.Contains(rule.data)
                       select c;
            if (rule.field == "Company")
                return customers.Where(c => c.CompanyName.Contains(rule.data));
            if (rule.field == "EmailAddress")
                return customers.Where(c => c.EmailAddress.Contains(rule.data));
            if (rule.field == "Last Modified")
            {
                DateTime result;
                if (!DateTime.TryParse(rule.data, out result))
                    return customers;
                if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
                    return customers;
                return customers.Where(c => c.ModifiedDate.Date == Convert.ToDateTime(rule.data).Date);
            }
            if (rule.field == "Telephone")
                return customers.Where(c => c.Phone.Contains(rule.data));
            return customers;
        }
开发者ID:reharik,项目名称:MvcJqGrid,代码行数:31,代码来源:Repository.cs

示例7: Filter

		private IQueryable<Poll> Filter(IQueryable<Poll> query, bool showHidden)
		{
			if (!showHidden)
			{
				var utcNow = DateTime.UtcNow;
				query = query.Where(p => p.Published);
				query = query.Where(p => !p.StartDateUtc.HasValue || p.StartDateUtc <= utcNow);
				query = query.Where(p => !p.EndDateUtc.HasValue || p.EndDateUtc >= utcNow);

				if (!QuerySettings.IgnoreMultiStore)
				{
					var currentStoreId = _storeContext.CurrentStore.Id;

					query =
						from p in query
						join sm in _storeMappingRepository.Table
						on new { c1 = p.Id, c2 = "Poll" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into p_sm
						from sm in p_sm.DefaultIfEmpty()
						where !p.LimitedToStores || currentStoreId == sm.StoreId
						select p;
				}
			}

			return query;
		}
开发者ID:boatengfrankenstein,项目名称:SmartStoreNET,代码行数:25,代码来源:PollService.cs

示例8: BulidQuery

 public IQueryable<User> BulidQuery(IQueryable<User> query, UserSearchModel model)
 {
     if (model.Role != null)
         query = query.Where(u => u.Role == model.Role);
     if (!string.IsNullOrEmpty(model.Search))
         query = query.Where(u => u.UserName.Contains(model.Search) || u.NiceName.Contains(model.Search));
     return query;
 }
开发者ID:miandai,项目名称:.Net-MVC-Blog,代码行数:8,代码来源:UserController.cs

示例9: GetQueryConditions

 /// <summary>
 /// 构造前台传递的查询条件
 /// </summary>
 /// <param name="queryable"></param>
 /// <param name="query"></param>
 /// <returns></returns>
 private IQueryable<User> GetQueryConditions(IQueryable<User> queryable, UserQuery query)
 {
     if (!string.IsNullOrWhiteSpace(query.Name))
         queryable = queryable.Where(p => p.Name.Contains(query.Name));
     if (query.Enabled != null)
         queryable = queryable.Where(p => p.Enabled == query.Enabled);
     return queryable;
 }
开发者ID:DukeCheng,项目名称:BeiDream,代码行数:14,代码来源:UserDomainService.cs

示例10: Filter

        private IQueryable<Applicant_QuickSearch.Projection> Filter(IQueryable<Applicant_QuickSearch.Projection> query)
        {
            query = query.Where(x => x.IsApplicant);

            if (Hired == ApplicantHiredFilter.Exclude)
            {
                query = query.Where(x => !x.IsHired);
            }
            else if (Hired == ApplicantHiredFilter.OnlyHired)
            {
                query = query.Where(x => x.IsHired);
            }

            string firstPart = "";
            string SecondPart = "";
            var isSplit = false;

            if (Term != null)
            {
                if (Term.Contains(","))
                {
                    firstPart = Term.Split(',')[0].Replace(" ", string.Empty);
                    SecondPart = Term.Split(',')[1].Replace(" ", string.Empty);
                    isSplit = true;
                }
                else if (Term.Contains(" "))
                {
                    firstPart = Term.Split(' ')[0].Replace(" ", string.Empty);
                    SecondPart = Term.Split(' ')[1].Replace(" ", string.Empty);
                    isSplit = true;
                }
            }

            Expression<Func<Applicant_QuickSearch.Projection, bool>> predicate = x =>
                            x.FullName1.StartsWith(Term)
                                || x.FullName2.StartsWith(Term)
                                || x.Companies.Any(y => y.StartsWith(Term))
                                || x.Skills.StartsWith(Term)
                                || x.TechnicalSkills.Any(y => y.StartsWith(Term))
                                || x.AttachmentNames.Any(y => y.StartsWith(Term));

            if (isSplit)
                predicate = predicate.Or(x => (x.FirstName.StartsWith(firstPart) && x.LastName.StartsWith(SecondPart))
                                  || (x.FirstName.StartsWith(SecondPart) && x.LastName.StartsWith(firstPart)));

            if (SearchInAttachments)
                predicate = predicate.Or(x => x.AttachmentContent.Any(y => y.StartsWith(Term)));

            query = query.Where(predicate);

            foreach (var slug in WithEvents.EmptyIfNull())
                query = query.Where(x => x.EventSlugs == slug);

            if (Highlighted)
                query = query.Where(x => x.IsHighlighted);

            return query;
        }
开发者ID:sofipacifico,项目名称:CommonJobs,代码行数:58,代码来源:ApplicantSearchParameters.cs

示例11: ReportBuildQuery

        public IQueryable<Country> ReportBuildQuery(IQueryable<Country> query)
        {
            query = query.Where(q => q.IsActive && !q.IsDeleted);
            if (!string.IsNullOrWhiteSpace(Name)) query = query.Where(q => q.Name.Contains(Name));
            if (!string.IsNullOrWhiteSpace(ShortCode)) query = query.Where(q => q.ShortCode.Contains(ShortCode));

            if (Pager.Size > 0) query = query.OrderBy(x => x.Updated).Skip(Pager.Skip()).Take(Pager.Size);
            return query;
        }
开发者ID:biggash730,项目名称:SemanticUI_Knockout_ASPMVC_Starter,代码行数:9,代码来源:Filters.cs

示例12: BuildQuery

        public IQueryable<City> BuildQuery(IQueryable<City> query)
        {

            if (Id > 0) query = query.Where(q => q.Id == Id);
            if (!string.IsNullOrWhiteSpace(Name)) query = query.Where(q => q.Name.Contains(Name));
            if (CountryId > 0) query = query.Where(q => q.CountryId == CountryId);
            query = query.Where(q => q.IsActive && !q.IsDeleted);
            if (Pager.Size > 0) query = query.OrderBy(x => x.Updated).Skip(Pager.Skip()).Take(Pager.Size);
            return query;
        }
开发者ID:biggash730,项目名称:Materialize_Knockout_ASPMVC_Starter,代码行数:10,代码来源:Filters.cs

示例13: GetQueryConditions

 /// <summary>
 /// 构造前台传递的查询条件
 /// </summary>
 /// <param name="queryable"></param>
 /// <param name="query"></param>
 /// <returns></returns>
 private IQueryable<Role> GetQueryConditions(IQueryable<Role> queryable, RoleQuery query)
 {
     if (!string.IsNullOrWhiteSpace(query.Name))
         queryable = queryable.Where(p => p.Name.Contains(query.Name));
     if (query.Enabled != null)
         queryable = queryable.Where(p => p.Enabled == query.Enabled);
     if (query.IsAdmin != null)
         queryable = queryable.Where(p => p.IsAdmin == query.IsAdmin);
     return queryable;
 }
开发者ID:DukeCheng,项目名称:BeiDream,代码行数:16,代码来源:RoleDomainService.cs

示例14: InvokesOncePerExecution

        public void InvokesOncePerExecution()
        {
            var list = new List<LuceneQueryStatistics>();

            documents = documents.CaptureStatistics(list.Add);

            documents.Where(doc => doc.Scalar == 1).ToList();
            documents.Where(doc => doc.Scalar != 1).ToList();

            Assert.That(list.Count, Is.EqualTo(2));
            Assert.That(list[0].TotalHits, Is.EqualTo(1));
            Assert.That(list[1].TotalHits, Is.EqualTo(2));
        }
开发者ID:Zaixu,项目名称:Lucene.Net.Linq,代码行数:13,代码来源:StatisticTests.cs

示例15: WhereDivision

        protected IQueryable<EduProgramProfileInfo> WhereDivision (int? divisionId, DivisionLevel divisionLevel, IQueryable<EduProgramProfileInfo> eduProgramProfiles)
        { 
            if (divisionId != null) {
                if (divisionLevel == DivisionLevel.EduProgram) {
                    return eduProgramProfiles.Where (epp => epp.EduProgram.DivisionId == divisionId);
                } 
                if (divisionLevel == DivisionLevel.EduProgramProfile) {
                    return eduProgramProfiles.Where (epp => epp.DivisionId == divisionId);
                }
            }

            return eduProgramProfiles;
        }
开发者ID:roman-yagodin,项目名称:R7.University,代码行数:13,代码来源:EduProgramProfileQuery.cs


注:本文中的IQueryable.Where方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。