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


C# List.FirstOrDefault方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            // This application creates a number of envelopes for the surface of the globe
            // The number of envelopes depends upon your delta for lat and long

            // Map sheets
            var mapSheets = new List<MapSheet>();

            double latitude = -90;
            double longitude = -180;

            // The amount of change per map sheet
            double deltaLat = 0.08;
            double deltaLong = 0.08;

            // Calculate how many maps we will need to make
            // 360 is the -180 to +180 long
            var iterationsLong = 360 / deltaLong;

            // Fill our maps
            for (int iLong = 0; iLong < iterationsLong; iLong++)
            {
                // 180 is the -90 to +90 lat
                var iterationsLat = 180 / deltaLat;

                // Populate our envelopes for each latitude in our iteration
                for (int iLat = 0; iLat < iterationsLat; iLat++)
                {
                    var mapSheet = new MapSheet()
                    {
                        Name = $"{iLat}",
                        AMGZone = "56",
                        Envelope = new Envelope(latitude, longitude, (latitude + deltaLat), (longitude + deltaLong)),
                        Number = iLat,
                        Scale = "1:25,000"
                    };
                    mapSheets.Add(mapSheet);

                    // Increment our Lat
                    latitude += deltaLat;
                }

                // Increment our long
                longitude += deltaLong;

                // Reset our lat
                latitude = -90;
            }

            // Query by coordinate
            var dateStart = DateTime.UtcNow;
            var map = mapSheets.FirstOrDefault(a => a.Envelope.Contains(new Coordinate(0.5, 0.5)));
            var dateEnd = DateTime.UtcNow;

            var elapsed = dateEnd - dateStart;

            Console.WriteLine($"{elapsed} to find one envelope in {mapSheets.Count} envelopes ({map.Name})");
            Console.ReadKey();
        }
开发者ID:darbio,项目名称:Geo_Tests,代码行数:59,代码来源:Program.cs

示例2: GetTopAuthorization

        public RoleAuthorization GetTopAuthorization(List<RoleAuthorization> list, RoleAuthorization info)
        {
            var parent = list.FirstOrDefault(t => t.FunctionId == info.ParentId);
            if (parent == null)
                return null;
            if (parent.Level == 1)
                return parent;

            return GetTopAuthorization(list, parent);
        }
开发者ID:lehprject,项目名称:sfjyDMS,代码行数:10,代码来源:RoleAuthorizationHelper.cs

示例3: FirstInvoice

        public Invoice FirstInvoice()
        {
            MyOrders = new List<Order>();
            var client1Orders = new FakeClient1Order().MyOrders;
            foreach (var order in client1Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);

            //Add it is is a subscriptions

            var firstOrderInvoice = new Invoice
            {

                InvoiceId = 1,

                OrderId = firstOrder.OrderId,
                ClientId = firstOrder.ClientId,
                OrderDate = firstOrder.OrderDate,
                DeliveryDate = firstOrder.DeliveryDate,
                CurrencyId = firstOrder.CurrencyId,

                CookerId = firstOrderCharge.CookerId,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                PlanTitle = firstOrderCharge.PlanTitle,
                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges,

                OrderModelTypeId = (int)Util.OrderModelType.Values.Transaction,
                CookerSubscriptionId = null,
                ServingPriceId = null,
                PlanId = null

            };
            return firstOrderInvoice;
        }
开发者ID:haithemaraissia,项目名称:GEvents,代码行数:52,代码来源:FakeClient1Invoices.cs

示例4: Match

        public override bool Match(GuideEnricherProgram enrichedGuideProgram, List<TvdbEpisode> episodes)
        {
            var episodeNumber = enrichedGuideProgram.GetValidEpisodeNumber();

            this.MatchAttempts++;

            var matchedEpisode = episodes.FirstOrDefault(x => x.SeasonNumber == episodeNumber / 100 && x.EpisodeNumber == episodeNumber % 100);
            if (matchedEpisode != null)
            {
                return this.Matched(enrichedGuideProgram, matchedEpisode);
            }
            
            return this.Unmatched(enrichedGuideProgram);
        }
开发者ID:Christoph21x,项目名称:ARGUS-TV-GuideEnhancer,代码行数:14,代码来源:NumericSeasonEpisodeMatchMethod.cs

示例5: Match

        public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
        {
            if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
            if (IsStringPropertyNull(guideProgram, guideProgram.Description, "Description")) return false;
            //
            var description = guideProgram.Description.ToLower();
            this.MatchAttempts++;
            var matchedEpisode = episodes.FirstOrDefault(x => !string.IsNullOrEmpty(x.EpisodeName) && new Regex(string.Concat("^", x.EpisodeName, "\\W"), RegexOptions.IgnoreCase).IsMatch(description));
            if (matchedEpisode != null)
            {
                return this.Matched(guideProgram, matchedEpisode);
            }

            return false;
        }
开发者ID:Christoph21x,项目名称:ARGUS-TV-GuideEnhancer,代码行数:15,代码来源:DescriptionStartsWithEpisodeTitleMatchMethod.cs

示例6: Match

        public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
        {
            if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
            if (IsStringPropertyNull(guideProgram, guideProgram.Description, "Description")) return false;
            //
            var match = quotedSentence.Match(guideProgram.Description);
            if (match == null || string.IsNullOrEmpty(match.Value))
                return false;

            this.MatchAttempts++;
            var matchedEpisode = episodes.FirstOrDefault(x => x.EpisodeName == match.Value);
            if (matchedEpisode != null)
            {
                return this.Matched(guideProgram, matchedEpisode);
            }
            return this.Unmatched(guideProgram);
        }
开发者ID:Christoph21x,项目名称:ARGUS-TV-GuideEnhancer,代码行数:17,代码来源:InQuotesInDescriptionMatchMethod.cs

示例7: FirstInvoice

        public Invoice FirstInvoice()
        {
            MyOrders = new List<Order>();
            var client2Orders = new FakeClient2Order().MyOrders;
            foreach (var order in client2Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);
            var firstOrderInvoice = new Invoice
            {
                InvoiceId = 2,
                OrderId = firstOrder.OrderId,
                ClientId = firstOrder.ClientId,
                OrderDate = firstOrder.OrderDate,
                DeliveryDate = firstOrder.DeliveryDate,
                CurrencyId = firstOrder.CurrencyId,

                CookerId = firstOrderCharge.CookerId,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                PlanTitle = firstOrderCharge.PlanTitle,
                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges
            };
            return firstOrderInvoice;
        }
开发者ID:haithemaraissia,项目名称:GEvents,代码行数:41,代码来源:FakeClient2Invoices.cs

示例8: Match

 public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
 {
     if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
     //
     Match match = null;
     int index = 0;
     do
     {
         match = regexes[index++].Match(guideProgram.Description);
     } while (string.IsNullOrEmpty(match.Value) && index < regexes.Count);
     if (match != null && !string.IsNullOrEmpty(match.Value))
     {
         this.MatchAttempts++;
         int seasonNumber = 0;
         int episodeNumber = 0;
         if (!int.TryParse(match.Groups["season"].Value, out seasonNumber))
         {
             // roman literal?
             seasonNumber = this.RomanToNumeric(match.Groups["season"].Value);
         }
         if (!int.TryParse(match.Groups["episode"].Value, out episodeNumber))
         {
             // roman literal?
             episodeNumber = this.RomanToNumeric(match.Groups["episode"].Value);
         }
         if (seasonNumber != 0 && episodeNumber != 0)
         {
             var matchedEpisode = episodes.FirstOrDefault(x => x.SeasonNumber == seasonNumber && x.EpisodeNumber == episodeNumber);
             if (matchedEpisode != null)
             {
                 return this.Matched(guideProgram, matchedEpisode);
             }
         }
     }
     return this.Unmatched(guideProgram);
 }
开发者ID:Christoph21x,项目名称:ARGUS-TV-GuideEnhancer,代码行数:36,代码来源:SeasonAndEpisodeInDescriptionMatchMethod.cs

示例9: RestoreAzureWebsiteDeploymentTest

        public void RestoreAzureWebsiteDeploymentTest()
        {
            // Setup
            SimpleWebsitesManagement channel = new SimpleWebsitesManagement();

            channel.GetWebSpacesThunk = ar => new WebSpaces(new List<WebSpace> { new WebSpace { Name = "webspace1" }, new WebSpace { Name = "webspace2" } });
            channel.GetSitesThunk = ar =>
            {
                if (ar.Values["webspaceName"].Equals("webspace1"))
                {
                    return new Sites(new List<Site> { new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = new SiteProperties
                        {
                            Properties = new List<NameValuePair>
                            {
                                new NameValuePair { Name = "repositoryuri", Value = "http" },
                                new NameValuePair { Name = "PublishingUsername", Value = "user1" },
                                new NameValuePair { Name = "PublishingPassword", Value = "password1" }
                            }
                        }}
                    });
                }

                return new Sites(new List<Site> { new Site { Name = "website2", WebSpace = "webspace2" } });
            };

            SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement();

            var deployments = new List<DeployResult> { new DeployResult { Id = "id1", Current = false }, new DeployResult { Id = "id2", Current = true } };
            deploymentChannel.GetDeploymentsThunk = ar => deployments;
            deploymentChannel.DeployThunk = ar =>
            {
                // Keep track of currently deployed id
                DeployResult newDeployment = deployments.FirstOrDefault(d => d.Id.Equals(ar.Values["commitId"]));
                if (newDeployment != null)
                {
                    // Make all inactive
                    deployments.ForEach(d => d.Complete = false);

                    // Set new to active
                    newDeployment.Complete = true;
                }
            };

            // Test
            RestoreAzureWebsiteDeploymentCommand restoreAzureWebsiteDeploymentCommand =
                new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
            {
                Name = "website1",
                CommitId = "id2",
                ShareChannel = true,
                CommandRuntime = new MockCommandRuntime(),
                CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionName }
            };

            restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
            Assert.AreEqual(1, ((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
            var responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.IsNotNull(responseDeployments);
            Assert.AreEqual(2, responseDeployments.Count());
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && d.Complete));
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && !d.Complete));

            // Change active deployment to id1
            restoreAzureWebsiteDeploymentCommand = new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
            {
                Name = "website1",
                CommitId = "id1",
                ShareChannel = true,
                CommandRuntime = new MockCommandRuntime(),
                CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionName }
            };

            restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
            Assert.AreEqual(1, ((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
            responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.IsNotNull(responseDeployments);
            Assert.AreEqual(2, responseDeployments.Count());
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && d.Complete));
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && !d.Complete));
        }
开发者ID:OctopusDeploy,项目名称:azure-sdk-tools,代码行数:80,代码来源:RestoreAzureWebsiteDeploymentTests.cs

示例10: FirstSubscriptionInvoice

        public Invoice FirstSubscriptionInvoice()
        {
            //TODO CHANGE IT TO REFLECT THE SUBSCRIPTION

            MyOrders = new List<Order>();
            var client1Orders = new FakeClient1SubscriptionsOrder().MyOrders;
            foreach (var order in client1Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);

            //Add it is is a subscriptions

            var firstOrderInvoice = new Invoice
            {

                InvoiceId = 10,

                #region Orders Fields
                OrderId = null,
                OrderDate = null,
                DeliveryDate = null,
                #endregion

                #region Subscription Fields

                SubscriptionStartDate = DateTime.Now.Date,
                SubscriptionEndDate = DateTime.Now.Date,
                SubscriptionInvoiceDate = DateTime.Now.Date,
                ClientSubscriptionId = 1,
                CookerSubscriptionId = 1,
                ServingPriceId = 3,
                PlanId = 1,
                PlanTitle = firstOrderCharge.PlanTitle,

                #endregion

                #region Common Fields

                ClientId = firstOrder.ClientId,
                CookerId = firstOrderCharge.CookerId,
                OrderModelTypeId = 2,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,
                CurrencyId = firstOrder.CurrencyId,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges,

                #endregion

            };
            return firstOrderInvoice;
        }
开发者ID:haithemaraissia,项目名称:GEvents,代码行数:68,代码来源:FakeSubscriptionsInvoices.cs

示例11: SetFixtures

        private static void SetFixtures(Series series, int season, IEnumerable<SeriesFixturesSummaryEntity> seriesFixturesResult)
        {
            var teams = new List<Team>();
            var seriesFixture = series.SeriesFixtures;
            foreach (var match in seriesFixturesResult.First(s => s.LeagueLevelUnitID == series.HtSeriesId).Matches)
            {
                var fixture = seriesFixture.FirstOrDefault(f => f.HtMatchId == match.MatchID);
                if (fixture == null)
                {
                    fixture = new SeriesFixture();
                    var homeTeam = teams.FirstOrDefault(t => t.TeamId == match.HomeTeamID);
                    if (homeTeam == null)
                    {
                        homeTeam = new Team
                                       {
                                           Country = series.Country,
                                           TeamId = match.HomeTeamID,
                                           TeamName = match.HomeTeamName
                                       };
                        teams.Add(homeTeam);
                    }

                    var awayTeam = teams.FirstOrDefault(t => t.TeamId == match.AwayTeamID);
                    if (awayTeam == null)
                    {
                        awayTeam = new Team
                                       {
                                           Country = series.Country,
                                           TeamId = match.AwayTeamID,
                                           TeamName = match.AwayTeamName
                                       };
                        teams.Add(awayTeam);
                    }
                    fixture.HtMatchId = match.MatchID;
                    fixture.AwayTeam = awayTeam;
                    fixture.HomeTeam = homeTeam;
                    fixture.MatchDate = match.MatchDate;
                    fixture.MatchRound = match.MatchRound;
                    fixture.Season = (short)season;
                    series.AddSeriesFixture(fixture);
                }
                fixture.AwayGoals = (short?)match.AwayGoals;
                fixture.HomeGoals = (short?)match.HomeGoals;
            }
        }
开发者ID:erikaspl,项目名称:WhoScored,代码行数:45,代码来源:MigrateToNhibernateDomainService.cs

示例12: FirstSubscriptionInvoice

        public Invoice FirstSubscriptionInvoice()
        {
            MySubscriptionsOrders = new List<OrderSubscription>();
            var client1SubscriptionsOrders = new FakeClient1SubscriptionsOrder().MyOrders;
            foreach (var order in client1SubscriptionsOrders)
            {
                MySubscriptionsOrders.Add(order);
            }

            var firstSubscriptionOrder = MySubscriptionsOrders.FirstOrDefault();
            if (firstSubscriptionOrder == null) return null;
            var subscriptionHelper = new SubscriptionHelper();
            var firstSubscriptionOrderCharge = new SubscriptionCharge().Calculate(firstSubscriptionOrder.ClientId, firstSubscriptionOrder);

            var firstSubscriptionOrderInvoice = new Invoice
            {

                InvoiceId = 20,

                #region Orders Fields
                //OrderId = null,
                OrderDate = null,
                DeliveryDate = null,
                #endregion

                #region Subscription Fields
                OrderId = firstSubscriptionOrder.OrderSubscriptionId,
                SubscriptionStartDate = DateTime.Now.Date,
                SubscriptionEndDate = DateTime.Now.Date.AddMonths(1),
                SubscriptionInvoiceDate = DateTime.Now.Date,

                ClientSubscriptionId = firstSubscriptionOrder.ClientSubscriptionId,
                CookerSubscriptionId = subscriptionHelper.GetCookerSubscription(firstSubscriptionOrder.ClientSubscriptionId).CookerSubscriptionId,
                ServingPriceId = subscriptionHelper.GetCookerServingPriceModel(firstSubscriptionOrder.ClientSubscriptionId).ServicePriceId,
                PlanId = firstSubscriptionOrder.PlanId,
                PlanTitle = subscriptionHelper.GetPlanTitle(firstSubscriptionOrder.PlanId),

                #endregion

                #region Common Fields

                ClientId = firstSubscriptionOrder.ClientId,
                CookerId = firstSubscriptionOrderCharge.CookerId,

                OrderModelTypeId = firstSubscriptionOrder.OrderTypeId,
                OrderTypeValue = firstSubscriptionOrderCharge.OrderTypeValue,

                PaymentMethodValue = firstSubscriptionOrderCharge.PaymentMethodValue,
                CurrencyId = firstSubscriptionOrder.CurrencyId,

                PromotionTitle = firstSubscriptionOrderCharge.PromotionTitle,
                PromotionPrice = firstSubscriptionOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstSubscriptionOrderCharge.PromotionCurrencyId,

                CouponTitle = firstSubscriptionOrderCharge.CouponTitle,
                CouponPrice = firstSubscriptionOrderCharge.CouponPrice,
                CouponCurrencyId = firstSubscriptionOrderCharge.CouponCurrencyId,

                SalesTax = firstSubscriptionOrderCharge.SalesTaxes,
                DeliveryFees = firstSubscriptionOrderCharge.DeliveryFee,
                SubTotal = firstSubscriptionOrderCharge.Subtotal,
                Total = firstSubscriptionOrderCharge.TotalCharges

                #endregion

            };
            return firstSubscriptionOrderInvoice;
        }
开发者ID:haithemaraissia,项目名称:PC,代码行数:68,代码来源:FakeSubscriptionsInvoices.cs

示例13: createRequisition

        /// <summary>
        /// CreateRequisition
        /// </summary>
        /// <param name="itemList">CartItems List (EmpID, ItemID, Qty)</param>
        /// <returns></returns>
        public int createRequisition(List<CartItems> itemList)
        {
            int result = 0;
            int ReqID = 0;

            if (itemList.FirstOrDefault() != null)
            {
                //create and add new requisition
                Requisition req = new Requisition();
                req.EmpID = itemList.First().EmpID;
                int empid = itemList.First().EmpID;
                req.DeptID = ctx.Employee.Where(x => x.EmpID == empid).First().DeptID;
                req.Date = DateTime.Now;
                req.StatusID = 1;
                ctx.Requisition.Add(req);
                ctx.SaveChanges();

                //obtain the ReqID of the newly added requisition
                List<Requisition> reqList = ctx.Requisition.Where(x => x.EmpID == empid).ToList();
                ReqID = reqList.Last().ReqID ;

                //create and add new requisition details
                foreach (CartItems item in itemList)
                {
                    RequisitionDetail reqDetail = new RequisitionDetail();
                    reqDetail.ReqID = ReqID;
                    reqDetail.ItemID = item.ItemID;
                    reqDetail.RequestQty = item.Qty;
                    ctx.RequisitionDetail.Add(reqDetail);
                }

                //delete items from request cart
                foreach (CartItems item in itemList)
                {
                    CartItems cartItem = ctx.CartItems.Where(x => x.EmpID == item.EmpID && x.ItemID == item.ItemID).FirstOrDefault();
                    ctx.CartItems.Remove(cartItem);
                }

            }

            int count = ctx.SaveChanges();

            if (count > 0)
                result = ReqID;

            if (result == ReqID)
            {
                //send notification:
                NotificationController nt = new NotificationController();
                nt.sendNotification(1, itemList.First().EmpID, Convert.ToString(ReqID));
            }

            return result;
        }
开发者ID:a0070011,项目名称:LogicUniversity_StationaryInventory,代码行数:59,代码来源:RequisitionController.cs

示例14: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session[Settings.Default.FlashSessionKey] != null)
            {
                this.FlashLiteralWrapper.Visible = true;
                this.FlashLiteral.Text = this.Session[Settings.Default.FlashSessionKey].ToString();
                this.Session[Settings.Default.FlashSessionKey] = null;
            }
            else
            {
                this.FlashLiteralWrapper.Visible = false;
            }

            this._petIdString = this.Request.QueryString["petid"];

            if (String.IsNullOrEmpty(this._petIdString))
            {
                this.StatsLiteral.Text = "Add a New Pet";
                this.SaveStatsButton.Text = "Save New Pet";
            }
            else
            {
                this.PhotoPanel.Visible = true;
            }

            this._userBucketName = String.Format(Settings.Default.BucketNameFormat, this.Context.User.Identity.Name, this._petIdString);
            this._itemName = this._petIdString ?? Guid.NewGuid().ToString();
            this._domainName = String.Format(Settings.Default.SimpleDbDomainNameFormat, this.Context.User.Identity.Name);

            if (!this.Page.IsPostBack)
            {
                List<int> years = new List<int>(100);
                for (int i = 0; i < 100; i++)
                {
                    years.Add(DateTime.Now.AddYears(i * -1).Year);
                }
                this.YearDropDownList.DataSource = years.OrderByDescending(y => y);
                this.YearDropDownList.DataBind();
                this.SelectMonth();
                this.SelectDay();

                Pet pet = default(Pet);
                List<string> files = new List<string>();
                if (!String.IsNullOrEmpty(this._petIdString))
                {
                    //
                    // Try to get the requested pet from the user's private domain
                    //
                    DomainHelper.CheckForDomain(this._domainName, _simpleDBClient);

                    GetAttributesRequest getAttributeRequest = new GetAttributesRequest()
                        .WithDomainName(this._domainName)
                        .WithItemName(this._itemName);
                    GetAttributesResponse getAttributeResponse = _simpleDBClient.GetAttributes(getAttributeRequest);
                    List<Attribute> attrs = null;
                    bool showPublic = false;

                    if (getAttributeResponse.IsSetGetAttributesResult())
                    {
                        attrs = getAttributeResponse.GetAttributesResult.Attribute;

                        showPublic = false;

                        //
                        // If we can't find it try the public domain
                        //
                        if (attrs.Count == 0)
                        {
                            showPublic = true;
                        }
                    }

                    if (showPublic)
                    {
                        Response.Redirect(String.Concat("PetProfile.aspx?petid", _petIdString));
                        return;
                    }

                    pet = new Pet
                    {
                        Name = attrs.First(a => a.Name == "Name").Value,
                        Birthdate = attrs.First(a => a.Name == "Birthdate").Value,
                        Sex = attrs.First(a => a.Name == "Sex").Value,
                        Type = attrs.First(a => a.Name == "Type").Value,
                        Breed = attrs.First(a => a.Name == "Breed").Value,
                        Likes = attrs.First(a => a.Name == "Likes").Value,
                        Dislikes = attrs.First(a => a.Name == "Dislikes").Value
                    };

                    this.Public.Checked = bool.Parse(attrs.First(a => a.Name == "Public").Value);

                    using (AmazonS3Client s3Client = new AmazonS3Client(Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim()))
                    {
                        BucketHelper.CheckForBucket(this._petIdString, s3Client);
                        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
                            .WithBucketName(this._userBucketName);
                        using (ListObjectsResponse listObjectsResponse = s3Client.ListObjects(listObjectsRequest))
                        {
                            files = listObjectsResponse.S3Objects.Select(o => String.Format(Settings.Default.S3BucketUrlFormat, this._userBucketName, o.Key)).ToList();
                            string firstPhoto = files.FirstOrDefault();
//.........这里部分代码省略.........
开发者ID:ksikes,项目名称:Amazon.Powershell,代码行数:101,代码来源:PetDetails.aspx.cs

示例15: BuscaForm

        public FormularioVersao BuscaForm(Data.DB _db, int? idFormulario, int idProjeto, bool IsPost, FormularioVersao _formPost)
        {
            Projeto _projeto = _db.getProjeto(idProjeto);

            //BUSCANDO OS FORMS DO FLUXO
            List<Formulario> _listaForms = listaForms(idProjeto).OrderBy(f => f.Ordem).ToList();

            //BUSCANDO AS VERSOES DOS FORMULARIOS
            List<FormularioVersao> _listaFormsVersao = new List<FormularioVersao>();
            foreach (var item in _listaForms)
            {
                _listaFormsVersao.Add(listaFormsVersao(item.Id, item.Ordem, _projeto.DtCriacao));
            }

            ViewBag.Forms = _listaFormsVersao;
            ViewBag.IdProjeto = idProjeto;

            FormularioVersao formRenderizado = _listaFormsVersao.FirstOrDefault(f => idFormulario == null || f.IdFormulario == idFormulario.Value);
            ViewBag.Message = formRenderizado.Nome;

            formRenderizado.Componentes = _db.getFormComponentes(formRenderizado.Id, idProjeto).OrderBy(e => e.Ordem).ToList();
            int idFluxo = Convert.ToInt32(Session["FluxoId"]);//Session?


            List<Resposta> ListaRespostasOld = new List<Resposta>();

            if (!IsPost)
                ListaRespostasOld = _db.getRespostas(formRenderizado.Id, idFluxo, idProjeto);

            Resposta respostaOld = null;
            FormularioComponente _comp;
            FormularioElemento _elem;
            foreach (var componente in formRenderizado.Componentes)
            {
                componente.Elementos = _db.getComponenteElementos(componente.IdComponente).OrderBy(e => e.Linha).ThenBy(e => e.Ordem).ToList();

                foreach (var elemento in componente.Elementos)
                {
                    if (IsPost)
                    {
                        //se a chave mudar para permitir ter varios componentes iguais, mudar aqui a busca para chave primaria!
                        _comp = _formPost.Componentes.FirstOrDefault(c => c.IdComponente == elemento.IdComponente);

                        //complemento no formulario postado deve existir, nem todos os componentes são mandados no Post                        
                        if (_formPost.Componentes.FirstOrDefault(c => c.IdComponente == elemento.IdComponente) != null)
                        {
                            _elem = _comp.Elementos.FirstOrDefault(e => e.Id == elemento.Id);
                            if (_elem != null)//nem todos os elementos vem no Post, por isso verificar se algum deve salvar
                                respostaOld = _elem.Respostas;
                        }
                    }
                    else
                        respostaOld = ListaRespostasOld.FirstOrDefault(r => r.IdComponenteElemento == elemento.Id && r.IdComponenteExpansao == 0); //soh o original do modelo do form tera expansao nula

                    if (respostaOld != null)
                        elemento.Respostas = respostaOld;

                    if (elemento.IdTipoElemento == 5 || elemento.IdTipoElemento == 7) //combo || radio
                        elemento.Valores = _db.getFormElementoValores(elemento.Id);
                }

                ComponenteExpansao compExp;
                respostaOld = null;
                //agora os expandidos, pegar os elementos e respostas
                if (componente.IsExpansivel)
                {
                    _comp = new FormularioComponente();
                    if (IsPost)
                    {
                        _comp = _formPost.Componentes.FirstOrDefault(c => c.Id == componente.Id); //pegando o componente que foi postado
                        componente.ListaComponenteExpansao = _comp.ListaComponenteExpansao; //pegar o que cliente modificou, no caso soh posta as expansoes modificadas
                    }

                    foreach (var item in componente.ListaComponenteExpansao)
                    {
                        item.Elementos = _db.getComponenteElementos(componente.IdComponente).OrderBy(e => e.Linha).ThenBy(e => e.Ordem).ToList();

                        foreach (var elemento in item.Elementos)
                        {
                            if (IsPost)
                            {
                                compExp = _comp.ListaComponenteExpansao.FirstOrDefault(ce => ce.Id == item.Id);
                                if (compExp != null)
                                {
                                    //buscar elementos da expansao
                                    _elem = compExp.Elementos.FirstOrDefault(e => e.Id == elemento.Id);
                                    if (_elem != null)//nem todos os elementos vem no Post, por isso verificar se algum deve salvar
                                        respostaOld = _elem.Respostas;
                                }
                            }
                            else
                                respostaOld = ListaRespostasOld.FirstOrDefault(r => r.IdComponenteElemento == elemento.Id && r.IdComponenteExpansao == item.Id); //todas expansoes tem id

                            if (respostaOld != null)
                                elemento.Respostas = respostaOld;

                            if (elemento.IdTipoElemento == 5 || elemento.IdTipoElemento == 7) //combo || radio
                                elemento.Valores = _db.getFormElementoValores(elemento.Id);
                        }
                    }
//.........这里部分代码省略.........
开发者ID:Marksys,项目名称:FormDynamicPOC,代码行数:101,代码来源:HomeController.cs


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