public void TestJoinOnly(IEnumerable<Foo> foos, IEnumerable<Foo> bars) { var actual = Factory.MemoryGroupJoin(foos.AsQueryable(), bars.AsQueryable(), f => f.Id, b => b.Id, (f, b) => new { Id = f.Id, BarCount = b.Count() }); var expected = foos.GroupJoin(bars, f => f.Id, i => i.Id, (f, b) => new { Id = f.Id, BarCount = b.Count() }); Assert.That(actual.ToArray(), Is.EquivalentTo(expected)); }
private Mock<IUnitOfWork> SetupUnitOfWork(IEnumerable<Form> data) { var unitOfWork = new Mock<IUnitOfWork>(); string[] includeNames = { "Topics", "Topics.Questions", "Topics.Questions.Answers" }; unitOfWork.Setup(u => u.Query<Form>(includeNames)).Returns(data.AsQueryable()); return unitOfWork; }
/// <summary> /// Finds the biggest common type of items in the list. /// </summary> /// <param name="items">The list.</param> /// <returns> /// The biggest common type. /// </returns> public static Type FindBiggestCommonType(IEnumerable items) { if (items == null) { return null; } Type type = null; foreach (var item in items) { if (item == null) { continue; } Type itemType = item.GetType(); if (type == null) { type = itemType; continue; } while (type != null && type.BaseType != null && !type.IsAssignableFrom(itemType)) { type = type.BaseType; } } if (type == null && items is IList) { type = items.AsQueryable().ElementType; } return type; }
public IEnumerable<ShipData> GetResult( IEnumerable<ShipData> list ) { if ( predicate == null ) throw new InvalidOperationException( "式がコンパイルされていません。" ); return list.AsQueryable().Where( predicate ).AsEnumerable(); }
public AnnualExpenseSummary(Client client, IEnumerable<Employee> employees) { ClientCompany = client; Employees = employees.AsQueryable(); CalculatStatistics(); }
public override void SetUp() { base.SetUp(); _patients = Fixture.CreateMany<Domain.Patient>(); _patientRepositoryMock.Setup(r => r.GetPatients()).Returns(_patients.AsQueryable()); }
public PredictionViewModel(Season currentSeason, Player currentLoggedInPlayer, IEnumerable<Comment> Comments) { LoggedInPlayer = currentLoggedInPlayer; Week week = currentSeason.GetCurrentWeekSeason(); CurrentWeekText = string.Format("This Week runs from {0} too {1}, This weeks cutoff for predictions is at {2} on the {3}", week.WeekStarts.ordinalDateShortDay(), week.WeekEnds.ordinalDateShortDay(), week.WeekCutOff.ToString("hh:mm tt"), week.WeekCutOff.ordinalDateShortDay()); ThisWeeksMatches = week.AllMatches().OrderBy(m =>m.MatchDate.Value); MatchOfTheWeek = week.MatchOfTheWeek; var PPs = new Dictionary<Player, IEnumerable<PlayerPrediction>>(); var PlayersWithCompletedPredictions = currentSeason.League.Players.Where(p => p.HasCompletedPredictions(week)); foreach (var p in PlayersWithCompletedPredictions.OrderByDescending(x=>x.CurrentTotalPoints(currentSeason))) { PPs.Add(p, p.GetPredictionsForThisWeek().OrderBy(m => m.Match.MatchDate.Value)); } PlayerPredictions = PPs; //comments CommentModel = new CommentingViewModel(7, week.Id, Comments.AsQueryable(), LoggedInPlayer); }
protected override void EstablishContext() { //Prepare supplied data collections suppliedListMetadata = GetSuppliedListMetadata(); suppliedStudentRow = GetSuppliedStudentRow(); suppliedPriorYearStudentRow = GetSuppliedPriorYearStudentList(); suppliedMetricVariants = GetSuppliedMetricVariants(); //Set up the mocks listMetadataProvider = mocks.StrictMock<IListMetadataProvider>(); studentListUtilitiesProvider = mocks.StrictMock<IStudentListUtilitiesProvider>(); trendRenderingDispositionProvider = mocks.StrictMock<ITrendRenderingDispositionProvider>(); metricStateProvider = mocks.StrictMock<IMetricStateProvider>(); metricVariantRepository = mocks.StrictMock<IRepository<MetricVariant>>(); windsorContainer = new WindsorContainer(); windsorContainer.Kernel.Resolver.AddSubResolver(new ArrayResolver(windsorContainer.Kernel)); RegisterProviders(windsorContainer); IoC.Initialize(windsorContainer); additionalPriorYearMetricProvider = IoC.Resolve<IAdditionalPriorYearMetricProvider>(); Expect.Call(metricVariantRepository.GetAll()) .Return(suppliedMetricVariants.AsQueryable()).Repeat.AtLeastOnce(); }
public void SetUp() { _documents = new List<Document> {new Document()}; var repository = MockRepository.GenerateMock<IRepository>(); _homeController = new HomeController(repository); repository.Stub(x => x.All<Document>()).Return(_documents.AsQueryable()); }
/// <summary> /// Obtem todos os dados de um objeto que só é conhecido em tempo de execução /// </summary> /// <param name="classType">Nome do tipo do objeto a ser gerado</param> /// <param name="includes">Dependencias desse objeto a serem incluídas.</param> /// <returns></returns> public virtual IQueryable <dynamic> ObterTodos(string classType = null, string[] includes = null) { if (!string.IsNullOrEmpty(classType)) { SetClass(classType); } IQueryable <dynamic> result = model?.AsQueryable(); if (includes != null) { foreach (string i in includes) { result = result.Include(i); } } return(result.NaoExcluidos()); }
public static IPackageRepositoryFactory Create(IEnumerable<IPackage> packages) { var packageRepositoryFactory = Substitute.For<IPackageRepositoryFactory>(); packageRepositoryFactory .CreateRepository("repository") .GetPackages() .Returns(packages.AsQueryable()); return packageRepositoryFactory; }
public TownRepositoryWithOptimizeRegionTestHelper( IEnumerable<Town> towns, IEnumerable<OptimizeRegion> regions) { this.towns = towns; this.regions = regions; townRepository.Setup(x => x.GetAll()).Returns(towns.AsQueryable()); townRepository.Setup(x => x.GetAllList()).Returns(townRepository.Object.GetAll().ToList()); townRepository.Setup(x => x.Count()).Returns(townRepository.Object.GetAll().Count()); controller = new RegionController(townRepository.Object, null, null, regionRepository.Object); }
private void OnNewsItemsAvailable(IEnumerable<NewsItem> newsItems, object userState) { IEnumerable<NewsItem> orderedItems = newsItems.AsQueryable().OrderByDescending(i => i.PublishDate); ViewActionResult result = View("List"); result.ViewData["Items"] = orderedItems.ToArray(); Task<ActionResult> task = (Task<ActionResult>)userState; task.Complete(result); }
public void Delete(IEnumerable<long> itemKeys) { _items.Query() .Join(itemKeys.AsQueryable(), item => item.ItemPKey, key => key, (item, key) => item) .ToList() .ForEach(itm => _items.Delete(itm)); _save.Save(); }
private IEnumerable<Node> CheckMetadataStringOperator(MappingToolDatabaseDataContext dbContext, IEnumerable<Node> nodes, GraphQueryMetadata metadataTest) { List<Node> filteredNodes = null; if (metadataTest.Operator.Equals("Contains", StringComparison.InvariantCultureIgnoreCase)) { IQueryable<Node> queryableNodes = nodes.AsQueryable(); var filteredMetadata = from dbMetadata in dbContext.udf_SearchMetadataContains(metadataTest.Name, metadataTest.Value) select dbMetadata; int counter = filteredMetadata.Count(); filteredNodes = nodes.Join(filteredMetadata, x => x.NodeUid, y => y.NodeUid, (a, b) => a).ToList(); } else if (metadataTest.Operator.Equals("FreeText", StringComparison.InvariantCultureIgnoreCase)) { IQueryable<Node> queryableNodes = nodes.AsQueryable(); var filteredMetadata = from dbMetadata in dbContext.udf_SearchMetadataFreeText(metadataTest.Name, metadataTest.Value) select dbMetadata; int counter = filteredMetadata.Count(); filteredNodes = nodes.Join(filteredMetadata, x => x.NodeUid, y => y.NodeUid, (a, b) => a).ToList(); } else { filteredNodes = new List<Node>(); foreach (Node node in nodes) { if (metadataTest.Operator.Equals("Equals", StringComparison.InvariantCultureIgnoreCase)) { if (node.Metadatas.Where(metadata => metadata.MetadataName == metadataTest.Name && metadata.MetadataValue.Contains(metadataTest.Value)).Count() > 0) { filteredNodes.Add(node); } } else if (metadataTest.Operator.Equals("NotEquals", StringComparison.InvariantCultureIgnoreCase)) { if (node.Metadatas.Where(metadata => metadata.MetadataName == metadataTest.Name && metadata.MetadataValue != metadataTest.Value).Count() > 0) { filteredNodes.Add(node); } } } } return filteredNodes; }
public (IEnumerable, IEnumerable <AggregateResult>) ApplyGroupingAndAggregates <T>(IEnumerable <T> data) { Request.Page = default; Request.Sorts = default; Request.PageSize = int.MaxValue; var result = data?.AsQueryable() .ToDataSourceResult(Request); return(result?.Data, result?.AggregateResults); }
public void FindResources(string searchTerm) { string searchTermLower = searchTerm.ToLowerInvariant(); data = DataManager.Resources.Where(item => (item.Title.ToLowerInvariant().Contains(searchTermLower) || item.Tags.ToLowerInvariant().Contains(searchTermLower))); results.ItemsSource = data; this.DataContext = data; OnSearchCompleted(new SearchEventArgs(data.AsQueryable())); }
private void ConnectMocksToDataStore(IEnumerable<Activities> data_store) { var data_source = data_store.AsQueryable<Activities>(); mock_activity_set.As<IQueryable<Activities>>().Setup(data => data.Provider).Returns(data_source.Provider); mock_activity_set.As<IQueryable<Activities>>().Setup(data => data.Expression).Returns(data_source.Expression); mock_activity_set.As<IQueryable<Activities>>().Setup(data => data.ElementType).Returns(data_source.ElementType); mock_activity_set.As<IQueryable<Activities>>().Setup(data => data.GetEnumerator()).Returns(data_source.GetEnumerator()); mock_context.Setup(a => a.Activities).Returns(mock_activity_set.Object); }
/// <summary> /// Initializes a new instance of the <see cref="TruncatedCollection{T}"/> class. /// </summary> /// <param name="source">The queryable collection to be truncated.</param> /// <param name="pageSize">The page size.</param> /// <param name="totalCount">The total count.</param> public TruncatedCollection(IEnumerable <T> source, int pageSize, long?totalCount, bool onlyCount) : base(PrepareBase(source?.AsQueryable(), pageSize)) { OnlyCount = onlyCount; if (pageSize > 0) { Initialize(pageSize); } _totalCount = totalCount; }
private static DbSet<BlockedISSN> CreateDbSet(IEnumerable<BlockedISSN> data) { var queryable = data.AsQueryable(); var mockSet = new Mock<DbSet<BlockedISSN>>(); mockSet.As<IQueryable<BlockedISSN>>().Setup(m => m.Provider).Returns(queryable.Provider); mockSet.As<IQueryable<BlockedISSN>>().Setup(m => m.Expression).Returns(queryable.Expression); mockSet.As<IQueryable<BlockedISSN>>().Setup(m => m.ElementType).Returns(queryable.ElementType); mockSet.As<IQueryable<BlockedISSN>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator()); return mockSet.Object; }
private static void TestFilterByName(string expected, IEnumerable<C> items, string operation, object value) { var genericFilter = new FilterCriteria("Name", operation, value); Console.WriteLine("genericFilter: " + genericFilter.Property + " " + genericFilter.Operation + " " + genericFilter.Value); var genericFilterHelper = new GenericFilterHelper(new DomainObjectModelMock()); var filterObject = genericFilterHelper.ToFilterObjects(new FilterCriteria[] { genericFilter }).Single(); Console.WriteLine("filterObject.FilterType: " + filterObject.FilterType.FullName); var filterExpression = genericFilterHelper.ToExpression<C>((IEnumerable<PropertyFilter>)filterObject.Parameter); var filteredItems = items.AsQueryable().Where(filterExpression).ToList(); Assert.AreEqual(expected, TestUtility.DumpSorted(filteredItems, item => item.Name ?? "<null>"), "Testing '" + operation + " " + value + "'."); }
private ObservableCollection<LogEntry> applyFilter(IEnumerable<LogEntry> items) { var result = items.AsQueryable(); if (cmbAppFilter.SelectedValue != null && !string.IsNullOrEmpty(cmbAppFilter.SelectedValue.ToString())) { result = result.Where(r => r.Application == cmbAppFilter.SelectedValue.ToString()); } if (cmbLevelFilter.SelectedValue != null && !string.IsNullOrEmpty(cmbLevelFilter.SelectedValue.ToString())) { result = result.Where(r => r.Level == cmbLevelFilter.SelectedValue.ToString()); } return new ObservableCollection<LogEntry>(result.ToList()); }
public void TestJoinWithPostExpression(IEnumerable<Foo> foos, IEnumerable<Bar> bars) { var joined = Factory.MemoryJoin(foos.AsQueryable(), bars.AsQueryable(), f => f.Id, b => b.Id, (f, b) => new { f.Id, FooName = f.Name, BarName = b.Name }) .Where(x => x.FooName != null) // todo: Влияет на сложность слияния, хочется, чтобы выполнялось до материализации. .Select(x => x.BarName) // todo: Влияет на объём материализуемых данных .ToArray(); var expected = foos.Join(bars, f => f.Id, b => b.Id, (f, b) => new { FooName = f.Name, BarName = b.Name }) .Where(x => x.FooName != null) .Select(x => x.BarName) .ToArray(); Assert.That(joined.ToArray(), Is.EquivalentTo(expected)); }
private static EfProductRepository ArrangeEfProductRepository(IEnumerable<Product> products) { var data = products.AsQueryable(); var mockSet = new Mock<DbSet<Product>>(); mockSet.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(data.ElementType); mockSet.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var mockContext = new Mock<EfProductContext>(); mockContext.Setup(m => m.ProductTable).Returns(mockSet.Object); return new EfProductRepository(mockContext.Object); }
private IQueryable<Election> FilterResult(string search, IEnumerable<Election> elections, List<string> columnFilters) { var results = elections.AsQueryable(); results = results.Where( x => (search == null || (x.Name != null && x.Name.ToLower().Contains(search.ToLower()) || x.Description != null && x.Description.ToLower().Contains(search.ToLower()))) && (columnFilters[0] == null || (x.Name != null && x.Name.ToLower().Contains(columnFilters[0].ToLower())))); return results; }
public static DataTable ToDataTable(IEnumerable list) { //创建属性的集合 List<PropertyInfo> pList = new List<PropertyInfo>(); //获得反射的入口 Type type = list.AsQueryable().ElementType; DataTable dt = new DataTable(); //把所有的public属性加入到集合 并添加DataTable的列 Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in list) { //创建一个DataRow实例 DataRow row = dt.NewRow(); //给row 赋值 pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); //加入到DataTable dt.Rows.Add(row); } return dt; }
/// <summary> /// Default implementation on how to refine a list of itmes based on the incoming url /// </summary> /// <param name="rootedQuery">The original list of items</param> /// <param name="url">The url which contains query</param> /// <returns>A refined list of the items</returns> public virtual IEnumerable ComposeQuery(IEnumerable rootedQuery, string url) { Debug.Assert(rootedQuery != null, "queryableRoot should not be null"); Debug.Assert(!String.IsNullOrEmpty(url), "url should not be null or empty"); // cast the queryableRoot to an IQueryable type to further compose the query IQueryable queryable = rootedQuery as IQueryable; if (queryable == null) { queryable = rootedQuery.AsQueryable(); } if (queryable != null) { IQueryable finalQueryable = QueryTranslator.Translate(queryable, url); return finalQueryable; } return rootedQuery; }
/// <summary> /// If the query operation has a result limit, this operation will compose Take(limit) on top /// of the specified results. /// </summary> /// <param name="results">The results that may need to be limited.</param> /// <param name="queryOperation">The query operation that was invoked to get the results.</param> /// <param name="limitedResults">The limited results. It will be <value>null</value> if there is no result limit.</param> /// <returns>True if a limited result query is returned, false otherwise.</returns> internal static bool TryComposeWithLimit(IEnumerable results, DomainOperationEntry queryOperation, out IEnumerable limitedResults) { int limit = ((QueryAttribute)queryOperation.OperationAttribute).ResultLimit; if (limit > 0) { IQueryable queryableResult = results.AsQueryable(); // Compose Take(limit) over the results. IQueryable limitQuery = Array.CreateInstance(queryOperation.AssociatedType, 0).AsQueryable(); limitQuery = limitQuery.Provider.CreateQuery( Expression.Call( typeof(Queryable), "Take", new Type[] { limitQuery.ElementType }, limitQuery.Expression, Expression.Constant(limit))); limitedResults = QueryComposer.Compose(queryableResult, limitQuery); return true; } limitedResults = null; return false; }
public static IProgramDefinition CreateDefinition(IEnumerable<IFileInfo> files, out Mock<IProgramDefinition> mock, Expression<Func<string, bool>> expressionToPassLogCheck = null, Expression<Func<string, bool>> expressionToPassCopyCheck = null, Expression<Func<string, bool>> expressionToPassBatchRun = null) { var definitionMock = new Mock<IProgramDefinition>(); if (expressionToPassLogCheck == null) expressionToPassLogCheck = s => true; if (expressionToPassCopyCheck == null) expressionToPassCopyCheck = s => true; if (expressionToPassBatchRun == null) expressionToPassBatchRun = s => true; definitionMock.Setup(a => a.GetFilesAsQueryable()).Returns(files.AsQueryable()); definitionMock.Setup(a => a.DoesLogFileIndicateCommonError(It.Is(expressionToPassLogCheck))).Returns(true); // only executes batch when function returns true definitionMock.Setup(a => a.CopySourceFile(It.Is(expressionToPassCopyCheck))).Returns(true); // batch file only executes when copy function returns false definitionMock.Setup(a => a.RunBatchFile(It.Is(expressionToPassBatchRun))).Returns(true); // batch file only executes when copy function returns false mock = definitionMock; return definitionMock.Object; }
public ResultTableModelView(Season currentSeason, Player currentLoggedInPlayer, IEnumerable<Comment> Comments) { LoggedInPlayer = currentLoggedInPlayer; week = currentSeason.GetLastWeekSeason(); MatchOfTheWeek = week.MatchOfTheWeek; ThisWeeksMatches = week.AllMatches().OrderBy(m => m.MatchDate.Value); var LeaguePlayers = currentSeason.GetActivePlayers(); var PlayerPointsCollection = new Dictionary<SimplePlayer, List<int>>(); foreach (var p in LeaguePlayers) { var playerLastWeekPredictions = currentSeason.GetPlayersPredictionsForLastWeek(p); //For each Match this week get the players point List<int> Points = new List<int>(); foreach (var m in ThisWeeksMatches) { //if user has predictions then get them and add them (this way if player has 5predictions //and there was 8 matches we correctly fill in the 0 scoring matches var Prediction = playerLastWeekPredictions.Where(pp => pp.Match == m).SingleOrDefault(); if(Prediction != null){ Points.Add(Prediction.PointsEarned()); }else{ Points.Add(0); } } PlayerPointsCollection.Add(new SimplePlayer(p), Points); } PlayersPoints = PlayerPointsCollection; //comments CommentModel = new CommentingViewModel(7, week.Id, Comments.AsQueryable(), currentLoggedInPlayer); }
public IEnumerable <PessFisicaJuridica> BuscaEmpregado(string pBusca) { int buscaLong; int.TryParse(pBusca, out buscaLong); if (buscaLong > 0) { IEnumerable <PessFisicaJuridica> empregadoPorMatricula; empregadoPorMatricula = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(@"SELECT nom_emprg nomeRazaoSocial, to_number(num_cpf_emprg) cpfCnpj, (select 'pFisica - Empregado' from dual) tipoCadastro, cod_emprs codigoEmpresa, to_number(num_rgtro_emprg) codigo, num_ctcor_emprg codigoContaCorrente, to_number(cod_banco) codigoBanco, to_number(cod_agbco) codigoAgencia, Num_Digvr_Emprg codigoDvContaCorrente, TIP_CTCOR_EMPRG codigotipoConta from EMPREGADO where NUM_RGTRO_EMPRG = " + buscaLong); empregadoPorMatricula.AsQueryable(); return(empregadoPorMatricula); } IEnumerable <PessFisicaJuridica> queryConvenente = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(@"select to_number(num_cgc_cpf) cpfCnpj, (trim(nom_convenente) || ' - ' || COD_CONVENENTE) nomeRazaoSocial, num_conta_corr codigoContaCorrente, to_number(dgv_convenente) codigoDvContaCorrente, (select 'pJuridica - Convenente' from dual) tipoCadastro, to_number(0) codigoEmpresa, cod_convenente codigo, tip_ctcor codigotipoConta, to_number(cod_banco) codigoBanco, to_number(cod_agbco) codigoAgencia from tb_convenente where nom_convenente LIKE '%" + pBusca.ToUpper() + "%'"); queryConvenente.AsQueryable(); IQueryable <PessFisicaJuridica> queryEmpregado; queryEmpregado = from emp in m_DbContext.EMPREGADO where emp.NOM_EMPRG.Contains(pBusca.ToUpper()) select new PessFisicaJuridica { cpfCnpj = emp.NUM_CPF_EMPRG, nomeRazaoSocial = emp.NOM_EMPRG, tipoCadastro = "pFisica - Empregado", codigo = emp.NUM_RGTRO_EMPRG, codigoEmpresa = emp.COD_EMPRS, // Somente a consulta de empregado deve retornar código de empresa. codigoAgencia = emp.COD_AGBCO, codigoBanco = emp.COD_BANCO, codigoContaCorrente = emp.NUM_CTCOR_EMPRG, codigoDvContaCorrente = emp.NUM_DIGVR_EMPRG, codigotipoConta = emp.TIP_CTCOR_EMPRG }; IQueryable <PessFisicaJuridica> queryDependente; queryDependente = from dpt in m_DbContext.DEPENDENTE where dpt.NOM_DPDTE.Contains(pBusca.ToUpper()) select new PessFisicaJuridica { cpfCnpj = dpt.NUM_CPF_DPDTE, nomeRazaoSocial = dpt.NOM_DPDTE, tipoCadastro = "pFisica - Dependente", codigo = dpt.NUM_IDNTF_DPDTE, codigoEmpresa = 0, codigoAgencia = 0, codigoBanco = 0, codigoDvContaCorrente = 0, codigoContaCorrente = "0", codigotipoConta = "0" }; IQueryable <PessFisicaJuridica> queryRpUniaoFss; queryRpUniaoFss = from ruf in m_DbContext.REPRES_UNIAO_FSS where ruf.NOM_REPRES.Contains(pBusca.ToUpper()) select new PessFisicaJuridica() { cpfCnpj = ruf.NUM_CPF_REPRES, nomeRazaoSocial = ruf.NOM_REPRES, tipoCadastro = "pFisica - Repres_uniao_fss", codigo = ruf.NUM_IDNTF_RPTANT, codigoEmpresa = 0, codigoAgencia = ruf.COD_AGBCO, codigoBanco = ruf.COD_BANCO, codigoContaCorrente = ruf.NUM_CTCOR_REPRES, cdTipoConta = ruf.TIP_CTCOR_REPRES, codigoDvContaCorrente = 0 }; foreach (var item in queryRpUniaoFss) { if (item.cdTipoConta >= 0) { item.codigotipoConta = item.cdTipoConta.ToString(); } } // pensões alimentícias IEnumerable <PessFisicaJuridica> queryEmpDpte = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(consultaPensaoAlimenticia + " where b.nom_dpdte like '%" + pBusca.ToUpper() + "%'" + " and " + exists); queryEmpDpte.AsQueryable(); var queryFinal = queryConvenente.Concat(queryEmpregado).Concat(queryDependente).Concat(queryRpUniaoFss).Concat(queryEmpDpte).Distinct(); return(queryFinal.Take(50).Distinct()); }
/// <summary> /// Creates a subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from. /// </summary> /// <typeparam name="T">The type of object the collection should contain.</typeparam> /// <param name="superset">The collection of objects to be divided into subsets. If the collection implements <see cref="IEnumerable{T}"/>, it will be treated as such.</param> /// <param name="pageNumber">The one-based index of the subset of objects to be contained by this instance.</param> /// <param name="pageSize">The maximum size of any individual subset.</param> /// <returns>A subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from.</returns> /// <seealso cref="PagedList{T}"/> public static async Task <IPagedList <T> > ToPagedListAsync <T>(this IEnumerable <T> superset, int pageNumber, int pageSize) { return(await ToPagedListAsync(superset.AsQueryable(), pageNumber, pageSize)); }
public static IQueryable <TOutput> MapperToOutPut <TOutput>(this IEnumerable data) where TOutput : class { return(data?.AsQueryable().ProjectTo <TOutput>(mapper.ConfigurationProvider)); }
public static IEnumerable <T> ApplyTo <T>(this ICriteria <T> me, IEnumerable <T> source) => me.ApplyTo(source.AsQueryable());
public IEnumerable <TDestination> ProjectTo <TDestination>(IEnumerable <object> source) { return(source.AsQueryable().ProjectTo <TDestination>()); }
public IEnumerable <T> ApplyFilter <T>(IEnumerable <T> query) { var expression = BuildExpression <T>(); return(expression != null?query.AsQueryable().Where(expression) : query); }
/// <inheritdoc cref="IQueryableExtensions.FilterFlexible{TItem}(IQueryable{TItem}, Func{TItem, string}, string)"/> public static IEnumerable <TElement> FilterFlexible <TElement>(this IEnumerable <TElement> source, Func <TElement, string> propertySelector, string filter) => (source?.AsQueryable()).FilterFlexible(propertySelector, filter);
/// <summary> /// Initializes a new instance of the <see cref="PagedList{T}"/> class that divides the supplied superset into subsets the size of the supplied pageSize. The instance then only containes the objects contained in the subset specified by index. /// </summary> /// <param name="superset">The collection of objects to be divided into subsets. If the collection implements <see cref="IQueryable{T}"/>, it will be treated as such.</param> /// <param name="index">The index of the subset of objects to be contained by this instance.</param> /// <param name="pageSize">The maximum size of any individual subset.</param> /// <exception cref="ArgumentOutOfRangeException">The specified index cannot be less than zero.</exception> /// <exception cref="ArgumentOutOfRangeException">The specified page size cannot be less than one.</exception> public PagedList(IEnumerable <T> superset, int index, int pageSize) : this(superset == null ? new List <T>().AsQueryable() : superset.AsQueryable(), index, pageSize) { }
public IActionResult Put(int key, [FromBody] ETagsCustomer eTagsCustomer, ODataQueryOptions <ETagsCustomer> queryOptions) { if (key != eTagsCustomer.Id) { return(BadRequest("The Id of customer is not matched with the key")); } IEnumerable <ETagsCustomer> appliedCustomers = customers.Where(c => c.Id == eTagsCustomer.Id); if (appliedCustomers.Count() == 0) { customers.Add(eTagsCustomer); return(Ok(eTagsCustomer)); } if (queryOptions.IfMatch != null) { IQueryable <ETagsCustomer> ifMatchCustomers = queryOptions.IfMatch.ApplyTo(appliedCustomers.AsQueryable()).Cast <ETagsCustomer>(); if (ifMatchCustomers.Count() == 0) { return(StatusCode(StatusCodes.Status412PreconditionFailed)); } } ETagsCustomer customer = appliedCustomers.Single(); customer.Name = eTagsCustomer.Name; customer.Notes = eTagsCustomer.Notes; customer.BoolProperty = eTagsCustomer.BoolProperty; customer.ByteProperty = eTagsCustomer.ByteProperty; customer.CharProperty = eTagsCustomer.CharProperty; customer.DecimalProperty = eTagsCustomer.DecimalProperty; customer.DoubleProperty = eTagsCustomer.DoubleProperty; customer.ShortProperty = eTagsCustomer.ShortProperty; customer.LongProperty = eTagsCustomer.LongProperty; customer.SbyteProperty = eTagsCustomer.SbyteProperty; customer.FloatProperty = eTagsCustomer.FloatProperty; customer.UshortProperty = eTagsCustomer.UshortProperty; customer.UintProperty = eTagsCustomer.UintProperty; customer.UlongProperty = eTagsCustomer.UlongProperty; customer.GuidProperty = eTagsCustomer.GuidProperty; customer.DateTimeOffsetProperty = eTagsCustomer.DateTimeOffsetProperty; return(Ok(customer)); }
public PagedResult(IEnumerable <T> list, IRequestParameters <T> request) : this(list?.AsQueryable(), request) { }
public IEnumerable <PessFisicaJuridica> BuscaCpfCnpj(string pBusca) { Int64 buscaInt; Int64.TryParse(pBusca, out buscaInt); long buscaLong; long.TryParse(pBusca, out buscaLong); IEnumerable <PessFisicaJuridica> queryEmpregado = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(@"SELECT nom_emprg nomeRazaoSocial, to_number(num_cpf_emprg) cpfCnpj, (select 'pFisica - Empregado' from dual), num_ctcor_emprg codigoContaCorrente, Num_Digvr_Emprg codigoDvContaCorrente, 'pFisica - Empregado' tipoCadastro, cod_emprs codigoEmpresa, num_rgtro_emprg codigo, to_number(cod_banco) codigoBanco, to_number(cod_agbco) codigoAgencia, TIP_CTCOR_EMPRG codigotipoConta FROM ATT.EMPREGADO WHERE NUM_CPF_EMPRG LIKE '%" + pBusca + "%'"); queryEmpregado.AsQueryable(); IQueryable <PessFisicaJuridica> queryDependente; queryDependente = from dpt in m_DbContext.DEPENDENTE where dpt.NUM_CPF_DPDTE == buscaLong select new PessFisicaJuridica { cpfCnpj = dpt.NUM_CPF_DPDTE, nomeRazaoSocial = dpt.NOM_DPDTE, tipoCadastro = "pFisica - Dependente", codigo = dpt.NUM_IDNTF_DPDTE, codigoEmpresa = 0, codigoAgencia = 0, codigoBanco = 0, codigotipoConta = "0", codigoContaCorrente = "0", codigoDvContaCorrente = 0 }; IQueryable <PessFisicaJuridica> queryRpUniaoFss; queryRpUniaoFss = from ruf in m_DbContext.REPRES_UNIAO_FSS where ruf.NUM_CPF_REPRES == buscaLong select new PessFisicaJuridica() { cpfCnpj = ruf.NUM_CPF_REPRES, nomeRazaoSocial = ruf.NOM_REPRES, tipoCadastro = "pFisica - Repres_uniao_fss", codigo = ruf.NUM_IDNTF_RPTANT, codigoEmpresa = 0, codigoAgencia = ruf.COD_AGBCO, codigoBanco = ruf.COD_BANCO, codigoContaCorrente = ruf.NUM_CTCOR_REPRES, cdTipoConta = ruf.TIP_CTCOR_REPRES, codigoDvContaCorrente = 0 }; foreach (var item in queryRpUniaoFss) { if (item.cdTipoConta >= 0) { item.codigotipoConta = item.cdTipoConta.ToString(); } } // pensões alimentícias IEnumerable <PessFisicaJuridica> queryEmpDpte = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(consultaPensaoAlimenticia + " where b.num_cpf_dpdte like '%" + pBusca.ToUpper() + "%'" + " and " + exists); queryEmpDpte.AsQueryable(); IEnumerable <PessFisicaJuridica> queryConvenente = m_DbContext.Database.SqlQuery <PessFisicaJuridica>(@"select to_number(num_cgc_cpf) cpfCnpj, (trim(nom_convenente) || ' - ' || COD_CONVENENTE) nomeRazaoSocial, num_conta_corr codigoContaCorrente, dgv_convenente codigoDvContaCorrente, (select 'pJuridica - Convenente' from dual) tipoCadastro, '0' codigoEmpresa, cod_convenente codigo, to_number(cod_banco) codigoBanco, to_number(cod_agbco) codigoAgencia, tip_ctcor codigotipoConta from tb_convenente where num_cgc_cpf LIKE '%" + pBusca + "%'"); queryConvenente.AsQueryable(); var queryFinal = queryEmpregado. Concat(queryDependente). Concat(queryRpUniaoFss). Concat(queryEmpDpte). Concat(queryConvenente); return(queryFinal.Take(50).Distinct()); }
//выбрать все записи из таблицы SearchEngine public IQueryable<SearchEngine> GetEngines() { return searchEngines.AsQueryable(); }
/// <summary> Returns an IEnumerable of anonymous type defined by <paramref name="properties"/>. </summary> public static IEnumerable <dynamic> SelectDynamic <T>(this IEnumerable <T> source, params string[] properties) { return(SelectProperties <T>(source.AsQueryable(), properties).Cast <dynamic>()); }
/// <summary> /// Creates a subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from. /// </summary> /// <typeparam name="T">The type of object the collection should contain.</typeparam> /// <typeparam name="TKey">Type For Compare</typeparam> /// <param name="superset">The collection of objects to be divided into subsets. If the collection implements <see cref="IEnumerable{T}"/>, it will be treated as such.</param> /// <param name="keySelector">Expression for Order</param> /// <param name="pageNumber">The one-based index of the subset of objects to be contained by this instance.</param> /// <param name="pageSize">The maximum size of any individual subset.</param> /// <returns>A subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from.</returns> public static IPagedList <T> ToPagedList <T, TKey>(this IEnumerable <T> superset, Expression <Func <T, TKey> > keySelector, int pageNumber, int pageSize) { return(new PagedList <T, TKey>(superset.AsQueryable(), keySelector, pageNumber, pageSize)); }
public static T FirstOrThrow <T>(this IEnumerable <T> query, string error_msg) => query.AsQueryable().FirstOrThrow(error_msg);
/// <summary> /// Initializes a new instance of the <see cref="TruncatedCollection{T}"/> class. /// </summary> /// <param name="source">The collection to be truncated.</param> /// <param name="pageSize">The page size.</param> public TruncatedCollection(IEnumerable <T> source, int pageSize) : base(PrepareBase(source?.AsQueryable(), pageSize)) { Initialize(pageSize); }
private void MockGetAllQuery(IEnumerable <Player> testData) { _getAllPlayersQueryMock.Setup(tr => tr.Execute(It.IsAny <GetAllCriteria>())).Returns(testData.AsQueryable()); }
public IActionResult Patch(int key, [FromBody] Delta <ETagsCustomer> patch, ODataQueryOptions <ETagsCustomer> queryOptions) { IEnumerable <ETagsCustomer> appliedCustomers = customers.Where(c => c.Id == key); if (appliedCustomers.Count() == 0) { return(BadRequest(string.Format("The entry with Id {0} doesn't exist", key))); } if (queryOptions.IfMatch != null) { IQueryable <ETagsCustomer> ifMatchCustomers = queryOptions.IfMatch.ApplyTo(appliedCustomers.AsQueryable()).Cast <ETagsCustomer>(); if (ifMatchCustomers.Count() == 0) { return(StatusCode(StatusCodes.Status412PreconditionFailed)); } } ETagsCustomer customer = appliedCustomers.Single(); patch.Patch(customer); return(Ok(customer)); }
/// <inheritdoc cref="IQueryableExtensions.GetPage{TElement}(IQueryable{TElement}, int, int)"/> public static IEnumerable <T> GetPage <T>(this IEnumerable <T> source, int pageNumber, int pageSize) => (source?.AsQueryable()).GetPage(pageNumber, pageSize);
public virtual async Task <IEnumerable <TEntity> > SaveAsync(IEnumerable <TEntity> entities) { await entities.AsQueryable().ForEachAsync(async e => await SaveAsync(e)); return(entities); }
public static IEnumerable <T> OrderBy <T>(this IEnumerable <T> enumerable, string orderBy) { return(enumerable.AsQueryable().OrderBy(orderBy).AsEnumerable()); }
public async Task DeleteAsync(IEnumerable <TEntity> entities) { await entities.AsQueryable().ForEachAsync(async e => await DeleteAsync(e)); }
/// <summary> /// Queryable page /// </summary> /// <param name="enumerable"></param> /// <param name="currentPageNumber"></param> /// <param name="pageSize"></param> /// <param name="totalMembersCount"></param> public QueryablePage(IEnumerable <T> enumerable, int currentPageNumber, int pageSize, int totalMembersCount) : this(enumerable.AsQueryable(), currentPageNumber, pageSize, totalMembersCount) { }
public PageableData( IEnumerable <T> source, IDictionary <string, object> properties) : this(source?.AsQueryable(), properties) { }
public DbAsyncEnumerable(IEnumerable <TEntity> enumerable) { Expression = enumerable.AsQueryable().Expression; _enumerable = enumerable; }
private static IVsPackageManager GetPackageManager(IEnumerable<IPackage> localPackages = null) { var fileSystem = new Mock<IFileSystem>(); var localRepo = new Mock<ISharedPackageRepository>(); localPackages = localPackages ?? new[] { PackageUtility.CreatePackage("P1", "0.9"), PackageUtility.CreatePackage("P2") }; localRepo.Setup(c => c.GetPackages()).Returns(localPackages.AsQueryable()); return new VsPackageManager(TestUtils.GetSolutionManager(), GetActiveRepository(), new Mock<IFileSystemProvider>().Object, fileSystem.Object, localRepo.Object, new Mock<IDeleteOnRestartManager>().Object, new Mock<VsPackageInstallerEvents>().Object); }
private IQueryable ExecuteQuery(IEnumerable query, HttpRequestMessage request, HttpActionDescriptor actionDescriptor) { Type originalQueryType = query.GetType(); Type elementClrType = TypeHelper.GetImplementedIEnumerableType(originalQueryType); if (elementClrType == null) { // The element type cannot be determined because the type of the content // is not IEnumerable<T> or IQueryable<T>. throw Error.InvalidOperation( SRResources.FailedToRetrieveTypeToBuildEdmModel, this.GetType().Name, actionDescriptor.ActionName, actionDescriptor.ControllerDescriptor.ControllerName, originalQueryType.FullName); } IEdmModel model = GetModel(elementClrType, request, actionDescriptor); if (model == null) { throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull); } ODataQueryContext queryContext = new ODataQueryContext(model, elementClrType); ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, request); ValidateQuery(request, queryOptions); // apply the query IQueryable queryable = query as IQueryable; if (queryable == null) { queryable = query.AsQueryable(); } return ApplyQuery(queryable, queryOptions); }
public static PaginatedListBuilder <Q, T> FormRequest(HttpRequest request, IEnumerable <Q> items, int defaultPerPage = 15, int defaultPage = 1, Func <Q, T> transform = null) { return(FormRequest(request, items?.AsQueryable(), defaultPerPage, defaultPage, transform)); }
/// <summary> /// Binds the chart attendance grid. /// </summary> /// <param name="chartData">The chart data.</param> private void BindChartAttendanceGrid( IEnumerable<Rock.Chart.IChartData> chartData ) { SortProperty sortProperty = gChartAttendance.SortProperty; if ( sortProperty != null ) { gChartAttendance.DataSource = chartData.AsQueryable().Sort( sortProperty ).ToList(); } else { gChartAttendance.DataSource = chartData.OrderBy( a => a.DateTimeStamp ).ToList(); } gChartAttendance.DataBind(); }
public PaginatedListBuilder(Uri baseUri, IEnumerable <Q> items, int perPage, int page, Func <Q, T> transform) : this(baseUri, items?.AsQueryable(), perPage, page, transform) { }