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


C# Tuple.Where方法代码示例

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


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

示例1: AddMenuItems

        /// <summary>
        /// Splits slash-separated strings into a submenu tree
        /// </summary>
        /// <param name="menu"></param>
        /// <param name="items"></param>
        private void AddMenuItems(ItemsControl menu, Tuple<KeyValuePair<int, string>, string[]>[] items)
        {
            foreach (var group in items.Where(x => x.Item2.Length > 1).GroupBy(x => x.Item2.First()))
            {
                var menuItem = new MenuItem { Command = null, CommandParameter = null, Header = group.Key };
                menu.Items.Add(menuItem);
                var subItems = group.Select(x => Tuple.Create(x.Item1, x.Item2.Skip(1).ToArray())).ToArray();
                AddMenuItems(menuItem, subItems);
            }

            foreach (var item in items.Where(x => x.Item2.Length == 1))
            {
                menu.Items.Add(new MenuItem { Command = SelectOptionCommand, CommandParameter = item.Item1, Header = item.Item2.Last() });
            }
        }
开发者ID:ValdemarOrn,项目名称:Polyhedrus,代码行数:20,代码来源:MenuSelector.xaml.cs

示例2: PocoData

        public PocoData(Type pocoType, string tableName, string keyspaceName, LookupKeyedCollection<string, PocoColumn> columns,
                        string[] partitionkeys, Tuple<string, SortOrder>[] clusteringKeys, bool caseSensitive, bool compact, bool allowFiltering)
        {
            if (pocoType == null) throw new ArgumentNullException("pocoType");
            if (tableName == null) throw new ArgumentNullException("tableName");
            if (columns == null) throw new ArgumentNullException("columns");
            if (partitionkeys == null) throw new ArgumentNullException("partitionkeys");
            if (clusteringKeys == null) throw new ArgumentNullException("clusteringKeys");
            PocoType = pocoType;
            TableName = tableName;
            Columns = columns;
            CaseSensitive = caseSensitive;
            CompactStorage = compact;
            AllowFiltering = allowFiltering;
            KeyspaceName = keyspaceName;
            _columnsByMemberName = columns.ToDictionary(c => c.MemberInfo.Name, c => c);
            PartitionKeys = partitionkeys.Where(columns.Contains).Select(key => columns[key]).ToList();
            ClusteringKeys = clusteringKeys.Where(c => columns.Contains(c.Item1)).Select(c => Tuple.Create(columns[c.Item1], c.Item2)).ToList();
            _primaryKeys = new HashSet<string>(PartitionKeys.Select(p => p.ColumnName).Concat(ClusteringKeys.Select(c => c.Item1.ColumnName)));

            MissingPrimaryKeyColumns = new List<string>();
            if (PartitionKeys.Count != partitionkeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
            if (ClusteringKeys.Count != clusteringKeys.Length)
            {
                MissingPrimaryKeyColumns.AddRange(partitionkeys.Where(k => !columns.Contains(k)));
            }
        }
开发者ID:Virus-X,项目名称:csharp-driver,代码行数:30,代码来源:PocoData.cs

示例3: DoPla

 private static double[] DoPla(double[] w, Tuple<double[], double>[] classified)
 {
     var misclassified = classified.Where(t => GetY(w, t.Item1) != t.Item2).ToArray();
       //Console.WriteLine("{0} misclassified.", misclassified.Length);
       //Console.Write(".");
       if (misclassified.Length == 0)
     return w;
       else
     return DoPla(NextW(w, misclassified[R.Next(misclassified.Length)]), classified);
 }
开发者ID:jschlitz,项目名称:LFD-SupportVectors,代码行数:10,代码来源:Program.cs

示例4: TrySelectDefault

 private IValueProvider[] TrySelectDefault(Tuple<IValueProvider, IProbe>[] itemsWithHighestScore, int max)
 {
     var defaultValueProviders = itemsWithHighestScore.Where(x => x.Item2.ExplicitPositiveReferencesCount == 0 && x.Item2.ReferencesCount == 0).Select(x => x.Item1).ToArray();
     if (defaultValueProviders.Count() == 1)
     {
         return new[] { defaultValueProviders.Single()};
     }
     throw new ItemsWithConflictingHighestScoreException(itemsWithHighestScore, max);
 }
开发者ID:Tetnacious,项目名称:ByContext,代码行数:9,代码来源:QueryEngine.cs

示例5: getLocationsOfObjectsThatBelongToCategory

 private static string[] getLocationsOfObjectsThatBelongToCategory(Dictionary<string, Category> categoriesToTransfer, Tuple<string, List<Category>, List<MediaContent>>[] locationCategoriesTuplesWithMedia)
 {
     var resultLocations = locationCategoriesTuplesWithMedia.Where(tuple => tuple.Item2.Any(cat => categoriesToTransfer.ContainsKey(cat.ID)))
                                                 .SelectMany(tuple =>
                                                     {
                                                         List<string> joiningValues = new List<string>();
                                                         joiningValues.Add(tuple.Item1);
                                                         joiningValues.AddRange(tuple.Item3.Select(mc => mc.RelativeLocation));
                                                         return joiningValues.ToArray();
                                                     }).ToArray();
     return resultLocations;
 }
开发者ID:kallex,项目名称:Caloom,代码行数:12,代码来源:PickCategorizedContentToConnectionImplementation.cs

示例6: ExecuteReloadConfig

        private void ExecuteReloadConfig(Tuple<string, Action<bool>>[] items)
        {
            List<string> requestTypes;
            List<string> distinctRequestsTypes;

            DataSet configuration = null;
            bool systemConfigurationLoaded = false;

            requestTypes = items
                .Select(tuple => tuple.Item1)
                .ToList();

            distinctRequestsTypes = requestTypes
                .Distinct()
                .OrderBy(type => requestTypes.LastIndexOf(type))
                .ToList();

            foreach (string type in distinctRequestsTypes)
            {
                string typeInner = type;

                if (type == m_configurationType.ToString())
                {
                    DisplayStatusMessage("Loading system configuration...", UpdateType.Information);
                    configuration = GetConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Augmented")
                {
                    DisplayStatusMessage("Augmenting current system configuration...", UpdateType.Information);
                    configuration = AugmentConfigurationDataSet(DataSource);

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "BinaryCache")
                {
                    DisplayStatusMessage("Loading binary cached configuration...", UpdateType.Information);
                    configuration = GetBinaryCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "XmlCache")
                {
                    DisplayStatusMessage("Loading XML cached configuration...", UpdateType.Information);
                    configuration = GetXMLCachedConfigurationDataSet();

                    // Update data source on all adapters in all collections
                    if ((object)configuration != null)
                        PropagateDataSource(configuration);
                }
                else if (type == "Startup")
                {
                    systemConfigurationLoaded = LoadStartupConfiguration();
                }
                else
                {
                    // No specific reload command was issued;
                    // load system configuration as normal
                    systemConfigurationLoaded = LoadSystemConfiguration();
                }

                foreach (Action<bool> callback in items.Where(tuple => tuple.Item1 == typeInner).Select(tuple => tuple.Item2))
                {
                    try
                    {
                        callback(systemConfigurationLoaded || (object)configuration != null);
                    }
                    catch (Exception ex)
                    {
                        DisplayStatusMessage("Failed to execute callback for ReloadConfig request of type {0}: {1}", UpdateType.Alarm, type, ex.Message);
                        LogException(ex);
                    }
                }

                // Spawn routing table calculation updates
                m_iaonSession.RecalculateRoutingTables();
            }
        }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:85,代码来源:ServiceHostBase.cs

示例7: InitializeConstructor

        private JsBlockStatement InitializeConstructor(INamedTypeSymbol type, string constructorName, Tuple<string, IParameterSymbol>[] parameters)
        {
            var block = new JsBlockStatement();
            block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Reference(SpecialNames.TypeInitializerTypeFunction));

            var parameterNames = parameters.Select(x => x.Item1);
            JsExpression[] arguments;
            if (!type.IsBuiltIn())
            {
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function().Body(Js.New(Js.Reference(SpecialNames.TypeInitializerTypeFunction), Js.This(), Js.Reference("arguments")).Return()));
            }
            else
            {
                arguments = parameters.Where(x => x.Item2 != null && x.Item2.IsBuiltIn()).Select(x => Js.Reference(x.Item1)).ToArray();
                block.Assign(GetFromPrototype(constructorName).Member(SpecialNames.New), 
                    Js.Function(parameterNames.Select(x => Js.Parameter(x)).ToArray())
                        .Body(Js.New(GetFromPrototype(constructorName).Member(SpecialNames.TypeField), Js.Array(arguments)).Return()));
            }

            return block;
        }
开发者ID:x335,项目名称:WootzJs,代码行数:22,代码来源:Idioms.cs

示例8: AddIOLink

            /// <summary>
            /// This adds ioIndex to one of finalLinks
            /// </summary>
            /// <param name="closestBrainIndex">Index of the brain that is closest to the IO.  There is no extra burden for linking to this one</param>
            /// <param name="brainBrainBurdens">
            /// Item1=Index of other brain
            /// Item2=Link resistance (burden) between closestBrainIndex and this brain
            /// </param>
            private static void AddIOLink(BrainBurden[] finalLinks, int ioIndex, double ioSize, int closestBrainIndex, Tuple<int, double>[] brainBrainBurdens)
            {
                // Figure out the cost of adding the link to the various brains
                Tuple<int, double>[] burdens = new Tuple<int, double>[finalLinks.Length];

                for (int cntr = 0; cntr < finalLinks.Length; cntr++)
                {
                    int brainIndex = finalLinks[cntr].Index;        // this is likely always the same as cntr, but since that object has brainIndex as a property, I feel safer using it

                    // Adding to the closest brain has no exta cost.  Adding to any other brain has a cost based on the
                    // distance between the closest brain and that other brain
                    double linkCost = 0d;
                    if (brainIndex != closestBrainIndex)
                    {
                        //TODO: Link every brain to every other brain, then get rid of this if statement
                        var matchingBrain = brainBrainBurdens.FirstOrDefault(o => o.Item1 == brainIndex);
                        if (matchingBrain == null)
                        {
                            continue;
                        }

                        linkCost = matchingBrain.Item2;
                    }

                    // LinkCost + IOStorageCost
                    burdens[cntr] = Tuple.Create(cntr, linkCost + BrainBurden.CalculateBurden(finalLinks[cntr].IOSize + ioSize, finalLinks[cntr].Size));
                }

                int cheapestIndex = burdens.
                    Where(o => o != null).
                    OrderBy(o => o.Item2).First().Item1;

                finalLinks[cheapestIndex].AddIOLink(ioIndex);
            }
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:42,代码来源:BrainLinks.xaml.cs

示例9: btnPolyUnionTest4_Click

        private void btnPolyUnionTest4_Click(object sender, RoutedEventArgs e)
        {

            // The main problem is that lines are slicing through the entire polygon.  Need to detect that, also get rid of colinear points

            try
            {
                ClearAllVisuals();

                Point3D[][] initial3D = new Point3D[3][];

                initial3D[0] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.9149519332283,2.55976103387392),
                    new Point3D(-17.1107881600685,0.515445435128346,3.40133335668073),
                    new Point3D(-17.3596515210729,-0.829632679480615,4.42103762371103),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.98385833288751) };

                initial3D[1] = new Point3D[] {
                    new Point3D(-16.1947246550931,-0.914951933228302,2.55976103387392),
                    new Point3D(-17.3283385073944,-2.17500700982897,4.9838583328875),
                    new Point3D(-17.3450427909807,-2.19357445878095,5.01957844043668),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857) };

                initial3D[2] = new Point3D[] {
                    new Point3D(-17.3204018787836,-4.49416933689273,6.02915227870288),
                    new Point3D(-16.4203453178512,-4.5492595275131,4.58613381891047),
                    new Point3D(-14.928909934653,-2.89147215820253,1.39687808008519),
                    new Point3D(-15.3066235822732,-2.3016870563904,1.74387733292857),
                    new Point3D(-17.341448388578,-2.52916527179157,5.16684630945675) };

                // Create some random triangles
                Point[][] initialPolys = new Point[3][];

                initialPolys[0] = new Point[] {
                    new Point(-1.70753174254516,-10.6978382660948),
                    new Point(-0.726945738693094,-12.3201526746214),
                    new Point(-2.36588629353582,-12.7943243278674),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-3.82425967044327,-12.7638803171038) };

                initialPolys[1] = new Point[] {
                    new Point(-1.70753174254517,-10.6978382660948),
                    new Point(-3.82425967044327,-12.7638803171038),
                    new Point(-3.85545055921974,-12.7943243278674),
                    new Point(-4.22195013459667,-12.7943243278674),
                    new Point(-2.65818579358351,-9.1250442852861) };

                initialPolys[2] = new Point[] {
                    new Point(-6.36793604229414,-12.7943243278674),
                    new Point(-5.84736974693176,-11.1743089731826),
                    new Point(-3.06250352298613,-8.45612745855601),
                    new Point(-2.65818579358351,-9.1250442852861),
                    new Point(-4.22195013459667,-12.7943243278674) };



                var feedsIntermediate = new Tuple<double, double, double, double>[]
                {
                    Tuple.Create(-1.70753174254516, -10.6978382660948, -0.726945738693094, -12.3201526746214),      //0
                    Tuple.Create(-0.726945738693094, -12.3201526746214, -2.36588629353582, -12.7943243278674),      //1
                    Tuple.Create(-2.36588629353582, -12.7943243278674, -3.85545055921974, -12.7943243278674),       //2
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -3.82425967044327, -12.7638803171038),       //3
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -1.70753174254516, -10.6978382660948),       //4
                    Tuple.Create(-1.70753174254517, -10.6978382660948, -3.82425967044327, -12.7638803171038),       //5
                    Tuple.Create(-3.82425967044327, -12.7638803171038, -3.85545055921974, -12.7943243278674),       //6
                    Tuple.Create(-3.85545055921974, -12.7943243278674, -4.22195013459667, -12.7943243278674),       //7
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -2.65818579358351, -9.1250442852861),       //8
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -1.70753174254517, -10.6978382660948),       //9
                    Tuple.Create(-6.36793604229414, -12.7943243278674, -5.84736974693176, -11.1743089731826),       //10
                    Tuple.Create(-5.84736974693176, -11.1743089731826, -3.06250352298613, -8.45612745855601),       //11
                    Tuple.Create(-3.06250352298613, -8.45612745855601, -2.65818579358351, -9.1250442852861),       //12
                    Tuple.Create(-2.65818579358351, -9.1250442852861, -4.22195013459667, -12.7943243278674),       //13
                    Tuple.Create(-4.22195013459667, -12.7943243278674, -6.36793604229414, -12.7943243278674)       //14
                }.Select(o => Tuple.Create(new Point(o.Item1, o.Item2), new Point(o.Item3, o.Item4))).ToArray();

                #region feeds intermediate dupes

                // Simplify duplication chains:
                //      Any point should only have one other match in the list
                //      If there is more than one match, the list should be able to be simplified

                List<Point> uniquePoints = new List<Point>();
                foreach (Point point in UtilityCore.Iterate(feedsIntermediate.Select(o => o.Item1), feedsIntermediate.Select(o => o.Item2)))
                {
                    if (!uniquePoints.Any(o => Math2D.IsNearValue(point, o)))
                    {
                        uniquePoints.Add(point);
                    }
                }

                var matchAttempt = uniquePoints
                    .Select(o => new { Point = o, Matches = feedsIntermediate.Where(p => Math2D.IsNearValue(o, p.Item1) || Math2D.IsNearValue(o, p.Item2)).ToArray() }).
                    OrderByDescending(o => o.Matches.Length).
                    ToArray();


                Tuple<Point, Point>[] feeds2 = feedsIntermediate.Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).ToArray();

//.........这里部分代码省略.........
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:101,代码来源:ShadowsWindow.xaml.cs

示例10: StitchSegmentsSprtCleanup_TOOMUCH

                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_TOOMUCH(Tuple<Point, Point>[] lineSegments)
                {
                    Tuple<Point, Point>[] cleaned = lineSegments.
                        Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).     // Remove single vertex matches
                        Select(o => o.Item1.X < o.Item2.X ? o : Tuple.Create(o.Item2, o.Item1)).     // Put the smaller x as item1
                        ToArray();

                    // Only return distinct segments
                    List<Tuple<Point, Point>> retVal = new List<Tuple<Point, Point>>();
                    foreach (var segment in cleaned)
                    {
                        if (!retVal.Any(o => Math2D.IsNearValue(segment.Item1, o.Item1) && Math2D.IsNearValue(segment.Item2, o.Item2)))
                        {
                            retVal.Add(segment);
                        }
                    }

                    // Exit Function
                    return retVal;
                }
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:20,代码来源:ShadowsWindow.xaml.cs

示例11: StitchSegmentsSprtCleanup_EXTENDCOLINEAR

                private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup_EXTENDCOLINEAR(Tuple<Point, Point>[] lineSegments)
                {
                    // Remove single vertex matches
                    var deduped = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();



                    // Remove double T joints (happens when two polygons are butted up next to each other.  Need to get rid of that middle segment)



                    // Removing colinear should be optional, it's an expense that may not be desired
                    bool merged = false;
                    do
                    {
                        // Find segment pairs that are colienar, and convert to a single segment (but only if they have no other segments using the point
                        // to be deleted)






                    } while (merged);









                    return null;

                }
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:36,代码来源:ShadowsWindow.xaml.cs

示例12: StitchSegmentsSprtCleanup

 private static List<Tuple<Point, Point>> StitchSegmentsSprtCleanup(Tuple<Point, Point>[] lineSegments)
 {
     // Remove single vertex matches
     return lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
 }
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:5,代码来源:ShadowsWindow.xaml.cs

示例13: StitchSegments

            private static Point[] StitchSegments(Tuple<Point, Point>[] lineSegments)
            {
                // Need to remove single vertex matches, or the loop below will have problems
                var fixedSegments = lineSegments.Where(o => !Math2D.IsNearValue(o.Item1, o.Item2)).ToList();
                if (fixedSegments.Count == 0)
                {
                    return null;
                }

                List<Point> retVal = new List<Point>();

                // Stitch the segments together into a polygon
                retVal.Add(fixedSegments[0].Item1);
                Point currentPoint = fixedSegments[0].Item2;
                fixedSegments.RemoveAt(0);

                while (fixedSegments.Count > 0)
                {
                    var match = FindAndRemoveMatchingSegment(fixedSegments, currentPoint);
                    if (match == null)
                    {
                        //TODO: If this becomes an issue, make a method that builds fragments, then the final polygon will hop from fragment to fragment
                        //TODO: Or, use Math2D.GetConvexHull - make an overload that rotates the points into the xy plane
                        //throw new ApplicationException("The hull passed in has holes in it");
                        return null;
                    }

                    retVal.Add(match.Item1);
                    currentPoint = match.Item2;
                }

                if (!Math2D.IsNearValue(retVal[0], currentPoint))
                {
                    //throw new ApplicationException("The hull passed in has holes in it");
                    return null;
                }

                if (retVal.Count < 3)
                {
                    return null;
                }

                // Exit Function
                return retVal.ToArray();
            }
开发者ID:charlierix,项目名称:AsteroidMiner,代码行数:45,代码来源:ShadowsWindow.xaml.cs

示例14: SetEntityState

        private void SetEntityState(EntityState newState, Tuple<IProperty, object>[] generatedValues)
        {
            // The entity state can be Modified even if some properties are not modified so always
            // set all properties to modified if the entity state is explicitly set to Modified.
            if (newState == EntityState.Modified)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: true);

                // Assuming key properties are not modified
                foreach (var keyProperty in EntityType.GetKey().Properties)
                {
                    _stateData.SetPropertyModified(keyProperty.Index, isModified: false);
                }
            }
            else if (newState == EntityState.Unchanged)
            {
                _stateData.SetAllPropertiesModified(_entityType.Properties.Count(), isModified: false);
            }

            var oldState = _stateData.EntityState;
            if (oldState == newState)
            {
                return;
            }

            // An Added entity does not yet exist in the database. If it is then marked as deleted there is
            // nothing to delete because it was not yet inserted, so just make sure it doesn't get inserted.
            if (oldState == EntityState.Added
                && newState == EntityState.Deleted)
            {
                newState = EntityState.Unknown;
            }

            _configuration.Services.StateEntryNotifier.StateChanging(this, newState);

            if (newState == EntityState.Added)
            {
                foreach (var generatedValue in generatedValues.Where(v => v != null && v.Item2 != null))
                {
                    this[generatedValue.Item1] = generatedValue.Item2;
                }
            }
            else
            {
                Contract.Assert(generatedValues == null);
            }

            _stateData.EntityState = newState;

            if (oldState == EntityState.Unknown)
            {
                _configuration.StateManager.StartTracking(this);
            }
            else if (newState == EntityState.Unknown)
            {
                // TODO: Does changing to Unknown really mean stop tracking?
                _configuration.StateManager.StopTracking(this);
            }

            _configuration.Services.StateEntryNotifier.StateChanged(this, oldState);
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:61,代码来源:StateEntry.cs

示例15: FilterIndexes


//.........这里部分代码省略.........
			Debug.Assert(last.LastModified != null);

			var lastEtag = last.Etag.Value;
			var lastModified = last.LastModified.Value;

			var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());

			var documentRetriever = new DocumentRetriever(null, context.ReadTriggers);

			var filteredDocs =
				BackgroundTaskExecuter.Instance.Apply(context, jsonDocs, doc =>
				{
					var filteredDoc = documentRetriever.ExecuteReadTriggers(doc, null, ReadOperation.Index);
					return filteredDoc == null ? new
					{
						Doc = doc,
						Json = (object)new FilteredDocument(doc)
					} : new
					{
						Doc = filteredDoc,
						Json = JsonToExpando.Convert(doc.ToJson())
					};
				});

			Log.Debug("After read triggers executed, {0} documents remained", filteredDocs.Count);

			var results = new Tuple<IndexToWorkOn, IndexingBatch>[indexesToWorkOn.Count];
			var actions = new Action<IStorageActionsAccessor>[indexesToWorkOn.Count];

			BackgroundTaskExecuter.Instance.ExecuteAll(context, indexesToWorkOn, (indexToWorkOn, i) =>
			{
				var indexLastInedexEtag = new ComparableByteArray(indexToWorkOn.LastIndexedEtag.ToByteArray());
				if (indexLastInedexEtag.CompareTo(lastIndexedEtag) >= 0)
					return;

				var indexName = indexToWorkOn.IndexName;
				var viewGenerator = context.IndexDefinitionStorage.GetViewGenerator(indexName);
				if (viewGenerator == null)
					return; // probably deleted

				var batch = new IndexingBatch();

				foreach (var item in filteredDocs)
				{
					if (FilterDocuments(item.Doc))
						continue;

					// did we already indexed this document in this index?
					var etag = item.Doc.Etag;
					if (etag == null)
						continue;

					if (indexLastInedexEtag.CompareTo(new ComparableByteArray(etag.Value.ToByteArray())) >= 0)
						continue;


					// is the Raven-Entity-Name a match for the things the index executes on?
					if (viewGenerator.ForEntityNames.Count != 0 &&
						viewGenerator.ForEntityNames.Contains(item.Doc.Metadata.Value<string>(Constants.RavenEntityName)) == false)
					{
						continue;
					}

					batch.Add(item.Doc, item.Json);

					if (batch.DateTime == null)
						batch.DateTime = item.Doc.LastModified;
					else
						batch.DateTime = batch.DateTime > item.Doc.LastModified
											? item.Doc.LastModified
											: batch.DateTime;
				}

				if (batch.Docs.Count == 0)
				{
					Log.Debug("All documents have been filtered for {0}, no indexing will be performed, updating to {1}, {2}", indexName,
						lastEtag, lastModified);
					// we use it this way to batch all the updates together
					actions[i] = accessor => accessor.Indexing.UpdateLastIndexed(indexName, lastEtag, lastModified);
					return;
				}
				if (Log.IsDebugEnabled)
				{
					Log.Debug("Going to index {0} documents in {1}: ({2})", batch.Ids.Count, indexToWorkOn, string.Join(", ", batch.Ids));
				}
				results[i] = Tuple.Create(indexToWorkOn, batch);

			});

			transactionalStorage.Batch(actionsAccessor =>
			{
				foreach (var action in actions)
				{
					if (action != null)
						action(actionsAccessor);
				}
			});

			return results.Where(x => x != null);
		}
开发者ID:andrewdavey,项目名称:ravendb,代码行数:101,代码来源:IndexingExecuter.cs


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