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


C# IEnumerable.First方法代码示例

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


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

示例1: AddFriends

 /// <summary>
 /// Creates new friend relationships between a list of people 
 /// All elements relate to the same player and game
 /// </summary>
 /// <param name="friends">A list of friends relationships</param>
 /// <returns>The result of the operation as a <see cref="T:Task{String}</returns>
 public async Task<string> AddFriends(IEnumerable<FriendLink> friends)
 {
     var friendList = friends.Select(fl => fl.FriendId).ToList();
     var gameId = friends.First().GameId;
     var playerId = friends.First().PlayerId;
     return await _httpHelper.Post(_token, $"api/friend/{gameId}/{playerId}/batch", JsonConvert.SerializeObject(friendList)); ;
 }
开发者ID:elastacloud,项目名称:Brisk4GamesSDK,代码行数:13,代码来源:FriendManager.cs

示例2: PartitionChangesForDocument

        private IEnumerable<IEnumerable<TextChange>> PartitionChangesForDocument(IEnumerable<TextChange> changes, SourceText originalSourceText)
        {
            var partitionedChanges = new List<IEnumerable<TextChange>>();
            var currentPartition = new List<TextChange>();

            currentPartition.Add(changes.First());
            var currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(changes.First().Span.End);

            foreach (var change in changes.Skip(1))
            {
                // If changes are on adjacent lines, consider them part of the same change.
                var changeStartLine = originalSourceText.Lines.GetLineFromPosition(change.Span.Start);
                if (changeStartLine.LineNumber >= currentPartitionEndLine.LineNumber + 2)
                {
                    partitionedChanges.Add(currentPartition);
                    currentPartition = new List<TextChange>();
                }

                currentPartition.Add(change);
                currentPartitionEndLine = originalSourceText.Lines.GetLineFromPosition(change.Span.End);
            }

            if (currentPartition.Any())
            {
                partitionedChanges.Add(currentPartition);
            }

            return partitionedChanges;
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:29,代码来源:AbstractLinkedFileMergeConflictCommentAdditionService.cs

示例3: GenerateMergeScript

 public string GenerateMergeScript(IEnumerable<InsertRowDesc> rows, bool united = false)
 {
     var script = string.Empty;
       if (rows.Count() == 0) // 0 rows
       {
     script = string.Empty;
       }
       else if (rows.Count() == 1) // only 1 row
       {
     script = GenerateMergeScript(rows.First());
       }
       else // above than 1 row
       {
     if (united == true)
     {
       CheckSchemaOnIdentity(rows);
       script = GenerateUnitedMergeScript(rows);
     }
     else
     {
       var sb = new StringBuilder();
       foreach (var row in rows)
       {
     sb.AppendLine(GenerateMergeScript(rows.First()));
       }
       script = sb.ToString();
     }
       }
       return script;
 }
开发者ID:popovegor,项目名称:tools,代码行数:30,代码来源:RowScriptGen.cs

示例4: PrintMostProfitableCategory

 private static void PrintMostProfitableCategory(
     IEnumerable<Order> allOrders, 
     IEnumerable<Product> allProducts, 
     IEnumerable<Category> allCategories)
 {
     // The most profitable category
     var category =
         allOrders.GroupBy(o => o.ProductId)
             .Select(
                 ordersGroup =>
                 new
                     {
                         ProductOrderedId = allProducts.First(p => p.Id == ordersGroup.Key).CategoryId, 
                         PriceOrdered = allProducts.First(p => p.Id == ordersGroup.Key).UnitPrice, 
                         Quantities = ordersGroup.Sum(productsOrdered => productsOrdered.Quantity)
                     })
             .GroupBy(product => product.ProductOrderedId)
             .Select(
                 productGroup =>
                 new
                     {
                         CategoryName = allCategories.First(c => c.Id == productGroup.Key).Name, 
                         TotalQuantity = productGroup.Sum(order => order.Quantities * order.PriceOrdered)
                     })
             .OrderByDescending(c => c.TotalQuantity)
             .First();
     Console.WriteLine("{0}: {1}", category.CategoryName, category.TotalQuantity);
 }
开发者ID:EBojilova,项目名称:CSharpHQC,代码行数:28,代码来源:OrdersMain.cs

示例5: IsEnabled

        /// <summary>
        /// Gets whether a feature path is valid for the features in the feature set
        /// </summary>
        /// <param name="features">Top-level features</param>
        /// <param name="featurePath">Feature path to the highest-level feature</param>
        /// <returns>Value indicating whether the feature path is valid for a feature in <paramref name="features"/></returns>
        /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="features"/> or <paramref name="featurePath"/> is null</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when <paramref name="featurePath"/> is empty</exception>
        public static bool IsEnabled(IEnumerable<IFeature> features, IEnumerable<string> featurePath)
        {
            Ensure.Argument.NotNull(features, "features");
            Ensure.Argument.NotNull(featurePath, "featurePath");
            Ensure.That<InvalidOperationException>(featurePath.Any(), "Feature Path must contain at least one top-level feature");

            // feature names are case insensitive
            IFeature current = FindFeature(features, featurePath.First());

            // skip the first value
            featurePath = featurePath.Skip(1);

            // loop through the entire path
            while (featurePath.Any())
            {
                // path was not found
                if (current == null)
                    return false;

                // see if the feature has subfeatures (Complex)
                var asComplex = current as IComplexFeature;
                if (asComplex == null) // feature doesn't have subfeatures, it passes
                    return true;

                current = FindFeature(asComplex.SubFeatures, featurePath.First());

                featurePath = featurePath.Skip(1);
            }

            return current != null;
        }
开发者ID:shibbard,项目名称:Multi-tenancy-Sample,代码行数:39,代码来源:Features.cs

示例6: Perform

        public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems)
        {
            RTMTaskItem task = null;
            List<string> temp_tags = new List<string> ();
            string s = null;

            if (items.Any()) {
                if (items.First () is RTMTaskItem)
                    task = (items.First () as RTMTaskItem);
                else if (items.First () is RTMTaskAttributeItem)
                    task = (items.First () as RTMTaskAttributeItem).Parent;
            }

            if (modifierItems.Any () && task != null) {
                foreach (Item item in modifierItems) {
                    s = GetText (item);
                    if (!String.IsNullOrEmpty(s))
                        temp_tags.Add (s);
                }

                Services.Application.RunOnThread (() => {
                    RTM.AddTags ((items.First () as RTMTaskItem).ListId, (items.First () as RTMTaskItem).TaskSeriesId,
                        (items.First () as RTMTaskItem).Id, String.Join (",", temp_tags.ToArray ()));
                });
            }
            yield break;
        }
开发者ID:jrudolph,项目名称:do-plugins,代码行数:27,代码来源:RTMAddTags.cs

示例7: InternalCall

 protected override Expression InternalCall(IEnumerable<Expression> args)
 {
     var f = (Function)args.First();
     args = PreProcessArguments(args.Skip(1));
     var list = ((ListExpression)args.First()).Elements;
     return list.Aggregate((acc, x) => f.Call(new Expression[] { acc, x }));
 }
开发者ID:tormaroe,项目名称:mist,代码行数:7,代码来源:ReduceFunction.cs

示例8: Forecast

        public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters)
        {
            if (period - 1 < 0)
                return null;

            double alpha = strategyParameters.Alpha;
            double beta = strategyParameters.Beta;
            double value;

            if (dataEntries.Count() < 3 || period < 3)
                value = dataEntries.ElementAt(0).Value;
            else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1)
                value = GenerateForecast(3, period, alpha, beta, dataEntries, dataEntries.First().Value, 0);
            else
                value = GenerateForecast(3, dataEntries.Count() + 1, alpha, beta, dataEntries, dataEntries.First().Value,
                                         0);

            return new ForecastEntry
                {
                    Period = period,
                    DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1),
                    ForecastValue = value,
                    ConfidenceIntervalLow = value,
                    ConfidenceIntervalHigh = value,
                    IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent
                };
        }
开发者ID:klaforce,项目名称:Silas,代码行数:27,代码来源:DoubleExponentialSmoothingStrategy.cs

示例9: DoRandomCharacter

        private static int DoRandomCharacter(IEnumerable<string> args)
        {
            uint count = 1;
            if (args.Any())
            {
                if (!uint.TryParse(args.First(), out count))
                {
                    Console.WriteLine("Invalid count: '{0}'", args.First());
                    PrintUsage();
                    return -1;
                }
            }

            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[8];
            for (uint i = 0; i < count; ++i)
            {
                crypto.GetBytes(bytes);
                long randomLong = BitConverter.ToInt64(bytes, 0);
                int randomIndex = (int)(Math.Abs(randomLong) % allowedCharacters.Length);
                char randomChar = allowedCharacters[randomIndex];

                Console.Write(randomChar);
            }

            Console.WriteLine();

            return 0;
        }
开发者ID:AdamLiechty,项目名称:random-csharp,代码行数:29,代码来源:Program.cs

示例10: Submit

        public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                var ext = Path.GetExtension(files.First().FileName);
                if (allowedFileExtensions.Contains(ext.Substring(1).ToLower()))
                {
                    var username = User.Identity.Name;

                    var fileName = username + ext;
                    var fullPath = Server.MapPath("~/img/Avatars/") + fileName;
                    files.First().SaveAs(fullPath);
                    var user = this.Data.Users.All().FirstOrDefault(u => u.UserName == username);
                    user.AvatarPath = "/img/Avatars/" + fileName;
                    this.Data.SaveChanges();
                }
                else
                {

                }

            }

            return RedirectToAction("ShowProfile");
        }
开发者ID:hatrox,项目名称:certificate-system,代码行数:25,代码来源:ProfileController.cs

示例11: SaveEvents

        private void SaveEvents(Guid eventSourceId,
            IEnumerable<UncommittedEvent> events)
        {
            string eventSourceName = events.First().GetType().ToString();
            long initialVersion = events.First().InitialVersionOfEventSource;
            long lastVersion = initialVersion + events.Count();

            NcqrsEventStoreContext storeContext = new NcqrsEventStoreContext(eventSourceId, account, prefix);
            Guid commitId = storeContext.BeginCommit();

            NcqrsEventSource lastSource = storeContext.LatestEventSource;
            if (lastSource == null)
            {
                lastSource = new NcqrsEventSource(eventSourceId,
                    initialVersion,
                    eventSourceName);

            }
            else if (lastSource.Version != initialVersion)
            {
                throw new ConcurrencyException(eventSourceId, initialVersion);
            }

            foreach (UncommittedEvent @event in events)
            {
                storeContext.Add(new NcqrsEvent(@event));
            }

            lastSource.Version = lastVersion;
            storeContext.SaveSource(lastSource);

            storeContext.EndCommit();
        }
开发者ID:VincentSchippefilt,项目名称:ncqrs,代码行数:33,代码来源:TableOnlyStore.cs

示例12: AirstrikePowerASEffect

		public AirstrikePowerASEffect(World world, Player p, WPos pos, IEnumerable<Actor> planes, AirstrikePowerASInfo info)
		{
			this.info = info;
			this.world = world;
			this.Owner = p;
			this.pos = pos;
			this.planes = planes;

			if (info.DisplayBeacon)
			{
				var distance = (planes.First().OccupiesSpace.CenterPosition - pos).HorizontalLength;

				beacon = new Beacon(
					Owner,
					pos - new WVec(WDist.Zero, WDist.Zero, world.Map.DistanceAboveTerrain(pos)),
					info.BeaconPaletteIsPlayerPalette,
					info.BeaconPalette,
					info.BeaconImage,
					info.BeaconPoster,
					info.BeaconPosterPalette,
					info.ArrowSequence,
					info.CircleSequence,
					info.ClockSequence,
						() => 1 - ((planes.First().OccupiesSpace.CenterPosition - pos).HorizontalLength - info.BeaconDistanceOffset.Length) * 1f / distance);

				world.AddFrameEndTask(w => w.Add(beacon));
			}
		}
开发者ID:GraionDilach,项目名称:OpenRA.Mods.AS,代码行数:28,代码来源:AirstrikePowerASEffect.cs

示例13: GetCurrencyConverter

        public static ICurrencyConvert GetCurrencyConverter(CurrencyEnum currencyType, IEnumerable<CurrencyExchange> theCurrencies)
        {
            ICurrencyConvert strategy = null;
            string currencyExchangeName = "GBP-";

            switch (currencyType)
            {
                case CurrencyEnum.GBP:
                    strategy = new PRCCurrencyConverter(CurrencyEnum.GBP, 1);
                    break;

                case CurrencyEnum.USD:
                    currencyExchangeName += "USD";
                    strategy = new PRCCurrencyConverter(CurrencyEnum.USD, (decimal)theCurrencies.First(x=>x.CurrencyExchangeName== currencyExchangeName).CurrencyExchangeRate);
                    break;

                case CurrencyEnum.EUR:
                    currencyExchangeName += "EUR";
                    strategy = new PRCCurrencyConverter(CurrencyEnum.EUR, (decimal)theCurrencies.First(x => x.CurrencyExchangeName == currencyExchangeName).CurrencyExchangeRate);
                    break;

                case CurrencyEnum.CAD:
                    currencyExchangeName += "CAD";
                    strategy = new PRCCurrencyConverter(CurrencyEnum.CAD, (decimal)theCurrencies.First(x => x.CurrencyExchangeName == currencyExchangeName).CurrencyExchangeRate);
                    break;

                default:
                    strategy = new PRCCurrencyConverter(CurrencyEnum.GBP, 1);
                    break;

            }

            return strategy;

        }
开发者ID:Weissenberger13,项目名称:web.portugalrentalcottages,代码行数:35,代码来源:CurrencyConverterFactory.cs

示例14: AxisAlignedBox3D

        public AxisAlignedBox3D(IEnumerable<Point3D> points)
        {
            if (points == null || !points.Any())
                throw new ArgumentException();

            // Compute minimal and maximal bounds.
            Min = points.First();
            Max = points.First();

            foreach (Point3D point in points)
            {
                if (point.X < Min.X)
                    Min.X = point.X;
                else if (point.X > Max.X)
                    Max.X = point.X;

                if (point.Y < Min.Y)
                    Min.Y = point.Y;
                else if (point.Y > Max.Y)
                    Max.Y = point.Y;

                if (point.Z < Min.Z)
                    Min.Z = point.Z;
                else if (point.Z > Max.Z)
                    Max.Z = point.Z;
            }
        }
开发者ID:tgjones,项目名称:nexus,代码行数:27,代码来源:AxisAlignedBox3D.cs

示例15: InitializeVariables

        private void InitializeVariables(IEnumerable<IVariable> variables)
        {
            ValidateInputProperties();

            Index1Variable = variables.OfType<IVariable>().First(v => v.Name == Index1VariableName);
            Index2Variable = variables.OfType<IVariable>().First(v => v.Name == Index2VariableName);
            XVariable = variables.OfType<IVariable<double>>().First(v => v.Name == XVariableName);
            YVariable = variables.OfType<IVariable<double>>().First(v => v.Name == YVariableName);
            ValuesVariable = variables.First(v => v.Name == ValuesVariableName);

            if(!string.IsNullOrEmpty(TimeVariableName))
            {
                TimeVariable = variables.First(v => v.Name == TimeVariableName);
            }

/*
            if(!XVariable.Arguments.SequenceEqual(YVariable.Arguments))
            {
                throw new NotSupportedException("Arguments used in X variable must be the same as in Y variable");
            }

            if (!XVariable.Arguments.SequenceEqual(ValuesVariable.Arguments))
            {
                throw new NotSupportedException("Arguments used in Values variable must be the same as in X and Y variables");
            }
*/
        }
开发者ID:lishxi,项目名称:_SharpMap,代码行数:27,代码来源:DiscreteGridPointCoverageBuilder.cs


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