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


C# IList.FirstOrDefault方法代码示例

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


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

示例1: TableInfo

        /// <summary>
        /// Initialises a new instance of the <see cref="TableInfo"/> class.
        /// </summary>
        /// <param name="columns">The columns that are mapped for the table.</param>
        /// <param name="identifierStrategy">The identifier strategy used by the table.</param>
        /// <param name="name">The name of the table.</param>
        /// <param name="schema">The database schema the table exists within (e.g. 'dbo'); otherwise null.</param>
        /// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception>
        /// <exception cref="MappingException">Thrown if no there is a problem with the column mappings.</exception>
        public TableInfo(
            IList<ColumnInfo> columns,
            IdentifierStrategy identifierStrategy,
            string name,
            string schema)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.columns = new ReadOnlyCollection<ColumnInfo>(columns);
            this.identifierStrategy = identifierStrategy;
            this.name = name;
            this.schema = schema;

            this.identifierColumn = columns.FirstOrDefault(c => c.IsIdentifier);

            this.insertColumnCount = columns.Count(c => c.AllowInsert);
            this.updateColumnCount = columns.Count(c => c.AllowUpdate);

            this.ValidateColumns();
        }
开发者ID:TrevorPilley,项目名称:MicroLite,代码行数:37,代码来源:TableInfo.cs

示例2: Handle

        public override int Handle(IFrame frame, IList<IFrame> frames)
        {
            if (!CanHandle(frame)) return 0;

            int frameScore = Configuration.NumberOfPins;

            List<int> extraRolls = new List<int>();

            var nextFrame = frames.FirstOrDefault(f => f.Sequence == frame.Sequence + 1);
            while(nextFrame != null && extraRolls.Count < Configuration.NumberOfRollsPerFrame)
            {
                if (IsStrike(nextFrame))
                {
                    extraRolls.Add(Configuration.NumberOfPins);
                    nextFrame = frames.FirstOrDefault(f => f.Sequence == frame.Sequence + 1);
                }
                else
                {
                    extraRolls.Add(
                        nextFrame.Rolls
                            .Where(r => r.Pins.HasValue)
                            .Select(r => r.Pins.Value).ToArray()[extraRolls.Count]
                        );
                }
            }

            return frameScore + extraRolls.Sum();
        }
开发者ID:crixo,项目名称:KataBowling,代码行数:28,代码来源:StrikeRuleLink.cs

示例3: CreateDocument

        public AccountTransactionDocument CreateDocument(Account account, string description, decimal amount, decimal exchangeRate, IList<AccountData> accounts, IList<ForeignCurrency> currencies)
        {
            var result = new AccountTransactionDocument { Name = Name, DocumentTypeId = Id };
            foreach (var accountTransactionType in TransactionTypes)
            {
                var transaction = AccountTransaction.Create(accountTransactionType);
                var amountRate = GetExchangeRate(accountTransactionType.ForeignCurrencyId, currencies);
                amount = amount * amountRate;
                transaction.UpdateAmount(amount, exchangeRate, accounts);
                transaction.UpdateAccount(MasterAccountTypeId, account.Id);
                if (accounts != null && accounts.Count > 0)
                {
                    if (transaction.SourceAccountTypeId != MasterAccountTypeId &&
                        transaction.SourceTransactionValue.AccountId == 0)
                    {
                        var ac = accounts.FirstOrDefault(x => x.AccountTypeId == transaction.SourceAccountTypeId);
                        if (ac != null) transaction.SetSourceAccount(ac.AccountTypeId, ac.AccountId);
                    }

                    if (transaction.TargetAccountTypeId != MasterAccountTypeId &&
                        transaction.TargetTransactionValue.AccountId == 0)
                    {
                        var ac = accounts.FirstOrDefault(x => x.AccountTypeId == transaction.TargetAccountTypeId);
                        if (ac != null) transaction.SetTargetAccount(ac.AccountTypeId, ac.AccountId);
                    }
                }
                if (!string.IsNullOrEmpty(description))
                {
                    transaction.UpdateDescription(description);
                }
                result.AccountTransactions.Add(transaction);
            }
            return result;
        }
开发者ID:GHLabs,项目名称:SambaPOS-3,代码行数:34,代码来源:AccountTransactionDocumentType.cs

示例4: GetArg

        public object GetArg(IList<string> args)
        {
            if(args.Count == 0)
                throw new Exception("too few arguments");

            var first = args.FirstOrDefault();

            var projectFilename = ZMFile.DefaultFilename;

            if (first.EndsWith(".zm"))
            {
                projectFilename = first;
                args.RemoveAt(0);
            }

            var targets = args.Where(x => !x.StartsWith("{")).ToList();
            var parameterString = args.FirstOrDefault(x => x.StartsWith("{")) ?? string.Empty;
            var parameters = new JObject();

            if(!string.IsNullOrWhiteSpace(parameterString))
                parameters = JObject.Parse(parameterString);

            var result = new RunArg(projectFilename, targets, parameters);
            return result;
        }
开发者ID:juankakode,项目名称:zenmake,代码行数:25,代码来源:RunRequestParser.cs

示例5: ExtractEdges

        static IList<Edge> ExtractEdges(IList<CodeReference> references, IList<Node> nodes)
        {
            var edges = new List<Edge>();

            var id = 0;
            foreach (var reference in references)
            {
                id += 1;
                var source = nodes.FirstOrDefault(node => node.label == reference.From);
                var target = nodes.FirstOrDefault(node => node.label == reference.To);

                if (source == null || target == null)
                {
                    continue;
                }

                edges.Add(new Edge {
                    id = $"e{id}",
                    source = source.id,
                    target = target.id
                });
            }

            return edges;
        }
开发者ID:thomasmichaelwallace,项目名称:EcLink,代码行数:25,代码来源:NetworkGraphBuilder.cs

示例6: findTrackContaining

 private RSTrackInfo findTrackContaining(IList<RSTrackInfo> songTracks, string[] preferences)
 {
     for(int i=0;i<preferences.Length;i++)
     {
         RSTrackInfo found = songTracks.FirstOrDefault(t => t.Name.Contains(preferences[i]));
         if (found != null) return found;
     }
     return songTracks.FirstOrDefault();
 }
开发者ID:joshbuhler,项目名称:RSTabExplorer,代码行数:9,代码来源:GuitarPath.cs

示例7: CombineExistingRecordsWithUpdatedRecords

        /// <summary>
        /// Combines and matches existing records with the updated records.
        /// </summary>
        /// <param name="updatedRecords">The calculated records with new wins, losses, and ties.</param>
        /// <param name="existingRecords">The existing records that will need to be updated.</param>
        /// <returns>List{UserRecord}. The collection of user records that should be updated or created.</returns>
        public static List<UserRecord> CombineExistingRecordsWithUpdatedRecords(IList<UserRecord> updatedRecords, IList<UserRecord> existingRecords)
        {
            var records = new List<UserRecord>();

            // Iterate through the updated records and checks if the user has a matching record that matches the record type
            foreach (var record in updatedRecords)
            {
                UserRecord recordToUpdate = null;

                if (record.RecordType == RecordType.Lifetime)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingLifetimeCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.Season)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingSeasonCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.SeasonType)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingSeasonTypeCondition(existingRecord, record));
                }
                else if (record.RecordType == RecordType.Week)
                {
                    recordToUpdate = existingRecords.FirstOrDefault(existingRecord => MatchingWeekCondition(existingRecord, record));
                }

                // Create a new record since the user does not have an existing record for the record type
                if (recordToUpdate == null)
                {
                    recordToUpdate = new UserRecord
                        {
                            Losses = record.Losses,
                            RecordType = record.RecordType,
                            Season = record.Season,
                            SeasonType = record.SeasonType,
                            Ties = record.Ties,
                            UserId = record.UserId,
                            Week = record.Week,
                            Wins = record.Wins
                        };
                }
                // Update the existing record type's wins, losses, and ties.
                else
                {
                    recordToUpdate.Losses = record.Losses;
                    recordToUpdate.Ties = record.Ties;
                    recordToUpdate.Wins = record.Wins;
                }

                records.Add(recordToUpdate);
            }

            return records;
        }
开发者ID:hecubu5,项目名称:sportpicks,代码行数:60,代码来源:RecordsManager.cs

示例8: assignClassData

        /// <summary>
        /// Consumes a line of data to populate a JobClass
        /// </summary>
        /// <param name="dataChunks">A collection of job class data points.</param>
        /// <param name="jobClass">A JobClass object to consume the line data.</param>
        /// <returns>Any remaining data after processing the JobClass.</returns>
        IEnumerable<string> assignClassData(IList<string> dataChunks, JobClass jobClass)
        {
            //the process order here is important, since we're relying on simple(ish) Regex
            //which may overlap one another

            // 1. code is always 4 consecutive integers
            string code = dataChunks.FirstOrDefault(c => FieldPatterns.ClassCode.IsMatch(c));
            if (!String.IsNullOrEmpty(code))
            {
                jobClass.Code = code;
                dataChunks.Remove(code);
            }
            // 2. grade is always 3 consecutive integers
            string grade = dataChunks.FirstOrDefault(c => FieldPatterns.Grade.IsMatch(c));
            if (!String.IsNullOrEmpty(grade))
            {
                jobClass.Grade = grade;
                dataChunks.Remove(grade);
            }
            // 3. bargaining unit code is always 3 consecutive capital letters
            string bu = dataChunks.FirstOrDefault(c => FieldPatterns.BargainingUnit.IsMatch(c));
            if (!String.IsNullOrEmpty(bu))
            {
                jobClass.BargainingUnit =
                    bargainingUnits.ContainsKey(bu) ?
                    bargainingUnits[bu] : new BargainingUnit() { Name = string.Empty, Code = bu };

                dataChunks.Remove(bu);
            }
            // 4. the remaining chunks are either part of the job title or part of a job step
            //    job step data is all numeric (integer or decimal numbers)
            //    so separate out the title parts and form the title
            decimal dec;
            var titleChunks = dataChunks.Where(c => !decimal.TryParse(c, out dec)).ToArray();
            string title = String.Join(" ", titleChunks).Trim();

            if (!String.IsNullOrEmpty(title))
            {
                jobClass.Title = title;
                foreach (var chunk in titleChunks)
                {
                    dataChunks.Remove(chunk);
                }
            }

            //the job step chunks are all that should remain
            return dataChunks;
        }
开发者ID:CityofSantaMonica,项目名称:SalarySchedules,代码行数:54,代码来源:CSMSalaryScheduleParser.cs

示例9: GetShopList

        /// <summary>
        /// Gets a sorted shop list from JSON string in expected format
        /// </summary>
        /// <param name="json">the json string</param>
        /// <returns>the shoplist</returns>
        public static ShopList GetShopList(string json, List<Product> allProducts, Customer customer, IList<Supermarket> markets)
        {
            JObject jObject = JObject.Parse(json);
            JToken jlistData = jObject["listData"];

            JToken jmarketName = jObject["supermarket"];
            string superName = jmarketName["superName"].ToString().Trim();
            Supermarket market = markets.FirstOrDefault(m => m.Name == superName) ?? markets[0];

            JToken jlistItems = jlistData["listItems"];//jlistData.First;
            var AllItems = jlistItems.Where(token => token.HasValues).ToList();//jlistItems.Children()[1];//.FirstOrDefault()["Id"];

            int temp;
            var tuplesStr =
                AllItems.OfType<JObject>()
                .Cast<IDictionary<string, JToken>>() //easier to handle as dictionary
                .Where(i => i.ContainsKey("Id") && i["Id"] !=null && !String.IsNullOrWhiteSpace(i["Id"].ToString())) //make sure ID is available
                .Select(i => new Tuple<string, string>( i["Id"].ToString() , i.ContainsKey("Quantity") ? i["Quantity"].ToString() : "1"))//get tuple with ID / quantity
                 .Where(t => int.TryParse(t.Item1, out temp) && int.TryParse(t.Item2, out temp))//parse to int
                 .ToList();//list is easier to debug

            var quantityByProductDic= new Dictionary<Product,int>();
            //add products to dictionary
            tuplesStr.ToList()
                .ForEach(t => quantityByProductDic.Add(allProducts.FirstOrDefault(p => p.Id == int.Parse(t.Item1)), int.Parse(t.Item2)));

            ShopList sl = Logics.GetShoppingList(quantityByProductDic, market, customer);

            return sl;
        }
开发者ID:GiladBaruchian,项目名称:ShopSmart,代码行数:35,代码来源:JsonToDalObject.cs

示例10: GetNestingParent

        public string GetNestingParent(string potentialChildFilePath, string potentialChildDirectory, IList<string> potentialParentProjectItems)
        {
            string fileName = Path.GetFileName(potentialChildFilePath);
            if (fileName != ".bowerrc") return null;

            return potentialParentProjectItems.FirstOrDefault(x => x == "bower.json");
        }
开发者ID:dennis7742,项目名称:WebEssentials2015,代码行数:7,代码来源:BowerRcNestingRule.cs

示例11: ConfirmPackList

        private void ConfirmPackList(TradevineGateway gateway, IList<Messages.SalesOrder> salesOrders, Dictionary<string, int> headerIndexes, List<string> row)
        {
            string packListID = string.Empty;

            try
            {
                packListID = row[headerIndexes["PackListID"]];
                packListID = packListID.Replace("ID:", string.Empty);
                var id = !string.IsNullOrEmpty(packListID) ? long.Parse(packListID) : (long?)null;
                var courier = row[headerIndexes["Courier"]];
                var trackingReference1 = row[headerIndexes["TrackingReference1"]];
                var trackingReference2 = row[headerIndexes["TrackingReference2"]];

                var salesOrder = salesOrders.FirstOrDefault(x => x.PackLists.Any(y => y.PackListID == id));
                if (null == salesOrder)
                    return;

                var packList = salesOrder.PackLists.Single(x => x.PackListID == id);
                packList.Courier = !string.IsNullOrEmpty(courier) ? int.Parse(courier) : (int?)null;
                packList.TrackingReference = trackingReference1;
                packList.TrackingReference2 = trackingReference2;

                packList.ConfirmOptions = new Messages.ConfirmOptions() { IsInvoiceEmailed = true, IsPackingSlipEmailed = true };

                var output = gateway.Sales.ConfirmPackList(packList);

                Console.WriteLine("Packlist {0} now has status {1}", output.PackListNumber, output.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error confirming packlist {0} : {1} : {2}", packListID, ex.Message, ex.StackTrace);
            }
        }
开发者ID:evan-williams,项目名称:ArtBlocks,代码行数:33,代码来源:ConfirmPackListsFromCsvFile.cs

示例12: FindClosestNode

        /// <summary>
        /// Find the node that's closest to the source node.
        /// </summary>
        /// <param name="source">The source node.</param>
        /// <param name="sharedParentNode">The parent node in common between the node in question and all the nodes in the list.</param>
        /// <param name="nodes">A list of nodes where we want to determine the closest to the source.</param>
        /// <returns>The node that is closest to the source.</returns>
        public static HtmlNode FindClosestNode(this HtmlNode source, HtmlNode sharedParentNode, IList<HtmlNode> nodes)
        {
            if (nodes.Count < 2) // don't even bother.
            {
                return nodes.FirstOrDefault();
            }
            int index = source.GetParentNodeUntil(sharedParentNode).GetIndex(); // get the index of our node, relative to the shared parent node.

            HtmlNode closest = null;
            int distance = int.MaxValue;

            foreach (HtmlNode currentNode in nodes)
            {
                int currentIndex = currentNode.GetParentNodeUntil(sharedParentNode).GetIndex(); // get the index of this node, relative to the shared parent node.
                int currentDistance;
                if (currentIndex > index)
                {
                    currentDistance = currentIndex - index;
                }
                else
                {
                    currentDistance = index - currentIndex;
                }
                if (currentDistance < distance)
                {
                    closest = currentNode;
                    distance = currentDistance;
                }
            }
            return closest;
        }
开发者ID:bevacqua,项目名称:Swarm,代码行数:38,代码来源:HtmlParsing.cs

示例13: AlgorithmManager

        public AlgorithmManager(IPoolManager poolManager, IObjectFactory objectFactory)
        {
            _storage = new List<IHashAlgorithmStatistics>();

            // add algorithms
            foreach (var pool in poolManager.GetAll())
            {
                var query = _storage.FirstOrDefault(x => x.Name == pool.Config.Coin.Algorithm);

                if (query != null)
                    continue;

                var statistics = objectFactory.GetHashAlgorithmStatistics(pool.Config.Coin.Algorithm);

                _storage.Add(statistics);
            }

            // assign pools to hash algorithms
            foreach (var item in _storage)
            {
                var algorithm = item;
                var pools = poolManager.GetAll().Where(p => p.Config.Coin.Algorithm == algorithm.Name);
                algorithm.AssignPools(pools);
            }
        }
开发者ID:icede,项目名称:CoiniumServ-develop,代码行数:25,代码来源:AlgorithmManager.cs

示例14: DefaultServerGridLayoutOptions

 public DefaultServerGridLayoutOptions(
     ContextualizedHelpers helpers,
     IList<RowType> rows,
     IList<KeyValuePair<string, string>> toolbars,
     Template<LayoutTemplateOptions> layoutTemplate,
     IEnumerable<Template<LayoutTemplateOptions>> subTemplates, 
     IHtmlContent mainContent,
     GridType type,
     string id,
     string prefix,
     GridErrorMessages messages,
     string cssClass,
     string caption,
     Type localizerType
     ) : base(rows, toolbars, layoutTemplate, subTemplates, mainContent)
 {
     this.helpers = helpers;
     Type = type;
     Messages = messages;
     Id = id;
     Prefix = prefix;
     CssClass = cssClass;
     Caption = caption;
     var first = rows.FirstOrDefault();
     MustAddButtonColumn = first.MustAddButtonColumn(helpers, Type== GridType.Batch);
     VisibleColumns = first.VisibleColumns(helpers, Type == GridType.Batch);
     LocalizerType = localizerType;
     Localizer = LocalizerType != null ? helpers.LocalizerFactory.Create(LocalizerType) : null;
 }
开发者ID:MvcControlsToolkit,项目名称:MvcControlsToolkit.ControlsCore,代码行数:29,代码来源:DefaultServerGridLayoutOptions.cs

示例15: SetAccessControlHeaders

        public static void SetAccessControlHeaders(this IContext context, IList<IAccessControlEntry> accessControl)
        {
            if (accessControl == null || accessControl.Count == 0) return;

            // For wildcards just add it
            if (accessControl.Count == 1 && accessControl[0].Origin == "*")
            {
                context.Response.SetAccessControl(accessControl[0]);
                return;
            }

            // If there's no Origin header in the request, no headers needed
            var origin = context.Request.GetOrigin();
            if (string.IsNullOrWhiteSpace(origin)) return;

            // If origin and host match we don't need headers
            var host = context.Request.Host;
            if (new Uri(origin).Authority.Equals(host, StringComparison.OrdinalIgnoreCase)) return;

            // Find a matching entry for the request origin
            var entry = accessControl.FirstOrDefault(e => e.Origin.Equals(origin, StringComparison.OrdinalIgnoreCase));
            if (entry != null)
            {
                context.Response.SetAccessControl(entry);
            }
        }
开发者ID:muratbeyaztas,项目名称:Simple.Web,代码行数:26,代码来源:ContextExtensions.cs


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