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


C# IEnumerable.FirstOrDefault方法代码示例

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


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

示例1: CreateStaff

 public ActionResult CreateStaff(IEnumerable<StaffView> staffs)
 {
     //產生加密誤密碼字串
     String sPwd = oDB.EncryptString(staffs.FirstOrDefault().DecryptionPassword);
     try
     {
         if (ModelState.IsValid)
         {
             var staff = new Staff
             {
                 Account = staffs.FirstOrDefault().Account,
                 Name = staffs.FirstOrDefault().Name,
                 Password = sPwd,
                 DecryptionPassword = staffs.FirstOrDefault().DecryptionPassword,
                 Role = staffs.FirstOrDefault().Role
             };
             if (TryUpdateModel(staff))
             {
                 db.Staff.Add(staff);
                 db.SaveChanges();
             }
         }
     }
     catch (System.Data.Entity.Validation.DbEntityValidationException ex)
     {
     };
     return Json(null);
 }
开发者ID:FTCEEP,项目名称:BarCode_MVC4,代码行数:28,代码来源:BarCodeWebStaffController.cs

示例2: UnionEnumerableExpressions

        public static Expression UnionEnumerableExpressions(IEnumerable<Expression> expressions)
        {
            var count = expressions.Count();
            if (count == 1) return expressions.FirstOrDefault();
            else if(count >= 2)
            {
        

                var expressionGroups = expressions.GroupBy(x => x.Type);

                if( expressionGroups.Count() != 1 ) throw new Exception("All expressions must be of the same type");

                var elementType = ReduceExpressionGeneration.GetTypeOfEnumerable( expressionGroups.First().Key );

                var unionInfos = typeof(Enumerable).GetMethods().Where(x => x.Name == "Union");
                var unionInfo = unionInfos.FirstOrDefault();
                var mi = unionInfo.MakeGenericMethod(elementType);

                var first = expressions.FirstOrDefault();
                var result = UnionEnumerableExpressions(expressions.Skip(1));

                return Expression.Call
                (
                    method: mi,
                    arg0: first,
                    arg1: result
                );
            }
            else
            {
                return null;
            }
        }
开发者ID:yonglehou,项目名称:Bermuda,代码行数:33,代码来源:Program.cs

示例3: Manager

 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="Profilers">The profilers.</param>
 public Manager(IEnumerable<IProfiler> Profilers)
 {
     Contract.Requires<ArgumentNullException>(Profilers != null, "Profilers");
     Profiler = Profilers.FirstOrDefault(x => !x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase));
     if (Profiler == null)
         Profiler = Profilers.FirstOrDefault(x => x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase));
 }
开发者ID:modulexcite,项目名称:Craig-s-Utility-Library,代码行数:11,代码来源:Manager.cs

示例4: findMatch

        private IFubuFile findMatch(IEnumerable<IFubuFile> files, string search)
        {
            var exactMatch = files.FirstOrDefault(x => x.RelativePath == search);
            if (exactMatch != null) return exactMatch;

            return files.FirstOrDefault(x => x.RelativePath.EndsWith(search));
        }
开发者ID:cothienlac86,项目名称:fubumvc,代码行数:7,代码来源:AssetFinderCache.cs

示例5: FindTypeMember

        private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, string nameToSearch, IMappingOptions mappingOptions)
        {
            MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch));
            if (pi != null)
                return pi;

            MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch));
            if (mi != null)
                return mi;

            pi = modelProperties.FirstOrDefault(prop => NameMatches(mappingOptions.SourceMemberNameTransformer(prop.Name), nameToSearch));
            if (pi != null)
                return pi;

            mi = getMethods.FirstOrDefault(m => NameMatches(mappingOptions.SourceMemberNameTransformer(m.Name), nameToSearch));
            if (mi != null)
                return mi;

            pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch)));
            if (pi != null)
                return pi;

            pi = getMethods.FirstOrDefault(m => NameMatches(m.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch)));
            if (pi != null)
                return pi;

            return null;
        }
开发者ID:firestrand,项目名称:AutoMapper,代码行数:28,代码来源:TypeMapFactory.cs

示例6: TransactionDetailsViewItem

        public TransactionDetailsViewItem(Model.Transaction transaction, 
            IEnumerable<Model.TransactionItem> transactionItems,
            IEnumerable<Model.TransactionIgnoredItem> transactionIgnoredItems,
            IEnumerable<Model.License> domainlessLicenseQuery,
            IEnumerable<Model.License> customerapplessLicenseQuery)
            : base(transaction)
        {
            PurchaserEmail = transaction.PurchaserEmail;

            PurchaserName = (transactionItems.Any(l => l.License != null)) ?
                transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName;

            OwnerName = (transactionItems.Any(l => l.License != null)) ?
                transactionItems.FirstOrDefault().License.OwningCustomer.Name : "None";

            SKUSummary = (from x in transactionItems select x.Sku).ToSummary(x => x.SkuCode, 99, ", ");

            IgnoredSummary = (from x in transactionIgnoredItems select x.Description).ToSummary(x => x, 99, ", ");

            StatusName = transaction.Status.GetDescription<Model.TransactionStatus>();

            DomainlessLicenses = (from x in domainlessLicenseQuery select x.ObjectId).ToList();

            CustomerapplessLicenses = (from x in customerapplessLicenseQuery select x.ObjectId).ToList();
        }
开发者ID:Natsui31,项目名称:keyhub,代码行数:25,代码来源:TransactionDetailsViewModel.cs

示例7: GetValueSomewhereInThePage

        private string GetValueSomewhereInThePage(HtmlNode document, string[] names, IEnumerable<HtmlNode> metaTags)
        {
            string result = null;

            var possibleNames = names.SelectMany(n => new[] { n, "og:" + n });

            var metaField = metaTags.FirstOrDefault(m => m.HasAttribute("property") && possibleNames.Contains(m.GetAttributeValue("property")));
            if (metaField == null)
            {
                metaField = metaTags.FirstOrDefault(m => m.HasAttribute("name") && possibleNames.Contains(m.GetAttributeValue("name")));
            }

            if (metaField != null)
            {
                result = metaField.GetAttributeValue("content");
            }

            if (String.IsNullOrWhiteSpace(result))
            {
                foreach (var name in possibleNames)
                {
                    var hiddenField = document.FindHiddenField(name);
                    if (hiddenField != null)
                    {
                        result = hiddenField.GetAttributeValue("value");
                        break;
                    }
                }
            }

            return result;
        }
开发者ID:AlexSugak,项目名称:EComWithCQRS,代码行数:32,代码来源:DefaultProductPageParser.cs

示例8: Query

        public IPagedList<OrderQueryModel> Query(IEnumerable<ExtendedQueryParameter> parameters, ICommerceDatabase db, int pageIndex, int pageSize)
        {
            if (pageIndex <= 1)
                pageIndex = 1;

            int num = 10;
            var numPara = parameters.FirstOrDefault(o => o.Name == "Num");
            if (numPara != null && numPara.Value != null && !string.IsNullOrEmpty(numPara.Value.ToString()))
                num = Convert.ToInt32(numPara.Value);
            decimal totalPrice = 100.0m;
            var totalPara = parameters.FirstOrDefault(o => o.Name == "TotalPrice");
            if (totalPara != null && totalPara.Value != null && !string.IsNullOrEmpty(totalPara.Value.ToString()))
                totalPrice = Convert.ToDecimal(totalPara.Value);

            var customerQuery = db.GetRepository<Customer>().Query();
            IQueryable<OrderQueryModel> query = db.GetRepository<Order>().Query()
                .Join(customerQuery,
                           order => order.CustomerId,
                           customer => customer.Id,
                           (order, customer) => new { Order = order, Customer = customer })
                .Select(o => new OrderQueryModel() { Customer = o.Customer, Order = o.Order })
                .Where(o => o.Order.Total > totalPrice)
                .OrderByDescending(o => o.Order.Total);
            var total = query.Count();
            var data = query.Skip(0).Take(num).ToArray();
            return new PagedList<OrderQueryModel>(data, pageIndex, pageSize, total);
        }
开发者ID:Wipcore,项目名称:Ecommerce,代码行数:27,代码来源:MostCostOrder.cs

示例9: ReplaceColor

        private static void ReplaceColor( BaseBrush in_Brush, IEnumerable<ColorPair> in_Colors )
        {
            if( (in_Brush == null) || (in_Colors == null) )
                return;

            if( in_Colors.Count( ) == 0 )
                return;

            if( in_Brush is NGraphics.Models.Brushes.GradientBrush )
            {
                GradientBrush typedBrush = in_Brush as GradientBrush;
                foreach( GradientStop stop in typedBrush.Stops )
                {
                    ColorPair pair = in_Colors.FirstOrDefault(x => (stop.Color.Red == x.OldColor.R) && (stop.Color.Green == x.OldColor.G) && (stop.Color.Blue == x.OldColor.B) && (stop.Color.Alpha == x.OldColor.A));
                    if( pair != null )
                        stop.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A);
                }
            }
            else if( in_Brush is NGraphics.Models.Brushes.SolidBrush )
            {
                SolidBrush typedBrush = in_Brush as SolidBrush;
                ColorPair pair = in_Colors.FirstOrDefault(x => (typedBrush.Color.Red == x.OldColor.R) && (typedBrush.Color.Green == x.OldColor.G) && (typedBrush.Color.Blue == x.OldColor.B) && (typedBrush.Color.Alpha == x.OldColor.A));
                if( pair != null )
                    typedBrush.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A);
            }
        }
开发者ID:BradChase2011,项目名称:Xamarin.Forms.Plugins,代码行数:26,代码来源:SvgImageRendererExtensions.cs

示例10: MapGameInfo

        public GameInfoViewModel MapGameInfo(GameDb game, IEnumerable<TeamDb> teams, Dictionary<string, string> users)
        {
            var result = new GameInfoViewModel();

            var homeTeam = teams.FirstOrDefault(x => x.EntityId == game.HomeTeam.Id);
            if (homeTeam != null)
            {
                result.HomeTeamName = homeTeam.Name;
                result.HomeTeamMediaId = homeTeam.MediaId;
                result.HomeTeamScore = game.HomeTeam.Score;
                if (!string.IsNullOrEmpty(game.HomeTeam.BestMemberId))
                    result.HomeTeamBestPlayer = users[game.HomeTeam.BestMemberId];
                result.HomeTeamScores = game
                    .HomeTeam.Members
                    .Where(x => x.Help != 0 || x.Score != 0)
                    .Select(x => MapGameInfoMember(x, users));
            }

            var guestTeam = teams.FirstOrDefault(x => x.EntityId == game.GuestTeam.Id);
            if (guestTeam != null)
            {
                result.GuestTeamName = guestTeam.Name;
                result.GuestTeamMediaId = guestTeam.MediaId;
                result.GuestTeamScore = game.GuestTeam.Score;
                if (!string.IsNullOrEmpty(game.GuestTeam.BestMemberId))
                    result.GuestTeamBestPlayer = users[game.GuestTeam.BestMemberId];
                result.GuestTeamScores = game
                    .GuestTeam.Members
                    .Where(x => x.Help != 0 || x.Score != 0)
                    .Select(x => MapGameInfoMember(x, users));
            }

            return result;
        }
开发者ID:AlexeyKryachko,项目名称:leagues,代码行数:34,代码来源:GamesMapper.cs

示例11: GetName

        private string GetName(IEnumerable<IRunElement> elements)
        {
            List<string> clues = new List<string>();

            var host = elements.FirstOrDefault(e => e is BaseHostElement);
            if (host != null)
            {
                clues.Add(host.Name);
            }

            var trace = elements.FirstOrDefault(e => e is TraceElement);
            if (trace != null)
            {
                clues.Add(trace.Name);
            }

            var name = string.Join(" ", clues);

            if (string.IsNullOrEmpty(name))
            {
                name = "Unknown";
            }

            return name;
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:25,代码来源:WebStackRunFrameFactory.cs

示例12: FromClaims

        public static ClaimsPrincipal FromClaims(IEnumerable<Claim> claims, bool allowMissing = false)
        {
            var amr = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationMethod);
            var sub = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
            var idp = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.IdentityProvider);
            var authTime = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationTime);

            var id = new ClaimsIdentity(Constants.BuiltInIdentityProvider);

            if (sub != null)
            {
                id.AddClaim(sub);
            }
            else
            {
                if (allowMissing == false)
                {
                    throw new InvalidOperationException("sub claim is missing");
                }
            }

            if (amr != null)
            {
                id.AddClaim(amr);
            }
            else
            {
                if (allowMissing == false)
                {
                    throw new InvalidOperationException("amr claim is missing");
                }
            }

            if (idp != null)
            {
                id.AddClaim(idp);
            }
            else
            {
                if (allowMissing == false)
                {
                    throw new InvalidOperationException("idp claim is missing");
                }
            }

            if (authTime != null)
            {
                id.AddClaim(authTime);
            }
            else
            {
                if (allowMissing == false)
                {
                    throw new InvalidOperationException("auth_time claim is missing");
                }
            }

            return new ClaimsPrincipal(id);
        }
开发者ID:Charmatzis,项目名称:IT4GOV,代码行数:59,代码来源:IdentityServerPrincipal.cs

示例13: CreateConnectionString

        private static ConnectionStringSettings CreateConnectionString(IEnumerable<Claim> claims)
        {
            string dblogin = claims.FirstOrDefault(c => c.Type == "dblogin").Value;
            string dbpass = claims.FirstOrDefault(c => c.Type == "dbpass").Value;
            string dbname = claims.FirstOrDefault(c => c.Type == "dbname").Value;

            return Database.CreateConnectionString("System.Data.SqlClient", @"LUNALAPPY\SQLEXPRESS", Cryptography.Decrypt(dbname), Cryptography.Decrypt(dblogin), Cryptography.Decrypt(dbpass));
        }
开发者ID:devalacarte,项目名称:kassysteem_nmct,代码行数:8,代码来源:ProductsDA.cs

示例14: ModifyMetadata

 public override void ModifyMetadata(EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata,
     IEnumerable<Attribute> attributes)
 {
     base.ModifyMetadata(metadata, attributes);
     var groupKeyAttribute = attributes.FirstOrDefault(a => typeof (TagsGroupKeyAttribute) == a.GetType()) as TagsGroupKeyAttribute;
     var cultureSpecificAttribute = attributes.FirstOrDefault(a => typeof(CultureSpecificAttribute) == a.GetType()) as CultureSpecificAttribute;
     EditorConfiguration["GroupKey"] = Helpers.TagsHelper.GetGroupKeyFromAttributes(groupKeyAttribute, cultureSpecificAttribute);
 }
开发者ID:boyanin,项目名称:Tags,代码行数:8,代码来源:TagsEditorDescriptor.cs

示例15: WriteEntry

      private static void WriteEntry(QueueEntry e, IEnumerable<Argument> arguments)
      {
         bool printProjectString = arguments.FirstOrDefault(a => a.Type == ArgumentType.PrintProjectString) != null ? true : false;
         bool showAll = arguments.FirstOrDefault(a => a.Type == ArgumentType.ShowAll) != null ? true : false;

         Console.Write(" Index {0}: {1}", e.Index, e.EntryStatusLiteral);
         if (e.SpeedFactor == 0)
         {
            Console.WriteLine();
         }
         else
         {
            Console.WriteLine(" {0} X min speed", e.SpeedFactor);
         }

         Console.WriteLine("  server: {0}:{1}; project: {2}", e.ServerIP, e.ServerPort, e.ProjectID);
         string misc4aEndian = e.Misc4aBigEndian ? "be" : "le";
         Console.WriteLine("  Folding: run {0}, clone {1}, generation {2}; benchmark {3}; misc: {4}, {5}, {6} ({7})",
                           e.ProjectRun, e.ProjectClone, e.ProjectGen, e.Benchmark, e.Misc1a, e.Misc1b, e.Misc4a, misc4aEndian);
         if (printProjectString)
         {
            Console.WriteLine("  Project: {0} (Run {1}, Clone {2}, Gen {3})", e.ProjectID, e.ProjectRun, e.ProjectClone, e.ProjectGen);
         }
         Console.WriteLine("  issue: {0:ddd MMM dd HH:mm:ss yyyy}; begin: {1:ddd MMM dd HH:mm:ss yyyy}", e.ProjectIssuedLocal, e.BeginTimeLocal);
         Console.Write("  ");
         if (e.EntryStatus == 3 || e.EntryStatus == 7)
         {
            Console.Write("end: {0:ddd MMM dd HH:mm:ss yyyy}; ", e.EndTimeLocal);
         }
         TimeSpan preferred = e.DueTimeLocal.Subtract(e.BeginTimeLocal);
         Console.WriteLine("due: {0:ddd MMM dd HH:mm:ss yyyy} ({1} days)", e.DueTimeLocal, Math.Ceiling(preferred.TotalDays));
         Console.WriteLine("  core URL: {0}", e.CoreDownloadUrl);
         Console.Write("  core number: 0x{0}", e.CoreNumber);
         Console.WriteLine("; core name: {0}", e.CoreName);
         Console.WriteLine("  CPU: {0},{1} {2}; OS: {3},{4} {5}", e.CpuType, e.CpuSpecies, e.CpuString, e.OsType, e.OsSpecies, e.OsString);
         Console.WriteLine("  smp cores: {0}; cores to use: {1}", e.NumberOfSmpCores, e.UseCores);
         Console.WriteLine("  tag: {0}", e.WorkUnitTag);
         if (e.Passkey.Length != 0 && showAll)
         {
            Console.WriteLine("  passkey: {0}", e.Passkey);
         }
         Console.WriteLine("  flops: {0} ({1:0.000000} megaflops)", e.Flops, e.MegaFlops);
         Console.WriteLine("  memory: {0} MB", e.Memory);
         Console.WriteLine("  client type: {0} {1}", e.RequiredClientType, e.RequiredClientTypeLiteral);
         string assignmentInfoEndian = e.AssignmentInfoBigEndian ? "be" : "le";
         if (e.AssignmentInfoPresent)
         {
            Console.WriteLine("  assignment info ({0}): {1:ddd MMM dd HH:mm:ss yyyy}; {2}", assignmentInfoEndian, e.AssignmentTimeStampLocal, e.AssignmentInfoChecksum);
         }
         Console.Write("  CS: {0}; ", e.CollectionServerIP);
         if (e.NumberOfUploadFailures != 0)
         {
            Console.Write("upload failures: {0}; ", e.NumberOfUploadFailures);
         }
         Console.WriteLine("P limit: {0}", e.PacketSizeLimit);
         Console.WriteLine("  user: {0}; team: {1}; ID: {2}; mach ID: {3}", e.FoldingID, e.Team, e.ID, e.MachineID);
         Console.WriteLine("  work/wudata_{0:00}.dat file size: {1}; WU type: {2}", e.Index, e.WuDataFileSize, e.WorkUnitType);
      }
开发者ID:harlam357,项目名称:hfm-net,代码行数:58,代码来源:QueueDisplay.cs


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