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


C# List.SingleOrDefault方法代码示例

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


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

示例1: RunManager

        private static void RunManager(InputConfig config)
        {
            try
            {
                var input = new DirectInput();
                var devices = new List<DeviceInstance>(input.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices));
                devices.AddRange(input.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices));

                var registeredDevices = new List<Tuple<Config.Input, Joystick>>();

                foreach (var inp in config.Inputs)
                {
                    var device = devices.SingleOrDefault(di => di.ProductGuid == new Guid(inp.Guid));
                    if (device == null)
                    {
                        throw new Exception($"Device \"{inp.Nickname}\" not found");
                    }

                    var joy = new Joystick(input, device.InstanceGuid);

                    registeredDevices.Add(Tuple.Create(inp, joy));
                }

                while (true)
                {
                    var frame = new InputFrame();
                    frame.GenerationTime = DateTime.Now;

                    foreach (var registeredDevice in registeredDevices)
                    {
                        var state = registeredDevice.Item2.GetCurrentState();

                        switch (registeredDevice.Item1.Type.ToUpper())
                        {
                            case "JOYSTICK":
                                frame.SubFrames.Add(new JoystickSubFrame(state));
                                break;
                            case "GAMEPAD":
                                frame.SubFrames.Add(new GamepadSubFrame(state));
                                break;
                        }
                    }

                    FrameCaptured?.Invoke(frame);
                }

            }
            catch (ThreadAbortException)
            {
                Console.Error.WriteLine("Input Manager Stopped at " + DateTime.Now.ToString("G"));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}\n\nInput Manager cannot continue", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
开发者ID:adam8797,项目名称:ROVControl2,代码行数:57,代码来源:InputManager.cs

示例2: getCategoriasTreeEnEmpresa

        public List<CategoriaDTO> getCategoriasTreeEnEmpresa(List<CategoriaDTO> lstCatsMontos, int idEmpresa, int? id = null)
        {
            
            var result = from r in lstCatsMontos
                            where ((id == null ? r.IdCategoriaPadre == null : r.IdCategoriaPadre == id) && r.Estado && r.IdEmpresa == idEmpresa)
                            select new CategoriaDTO
                            {
                                IdCategoria = r.IdCategoria,
                                Nombre = r.Nombre,
                                Orden = r.Orden,
                                Estado = r.Estado,
                                IdCategoriaPadre = r.IdCategoriaPadre,
                                IdEmpresa = r.IdEmpresa,
                                Presupuesto = lstCatsMontos.SingleOrDefault(x => x.IdCategoria == r.IdCategoria).Presupuesto
                            };
            List<CategoriaDTO> categoriasTree = result.AsEnumerable<CategoriaDTO>().OrderBy(x => x.Orden).ToList<CategoriaDTO>();

            foreach (CategoriaDTO obj in categoriasTree)
            {
                obj.Hijos = getCategoriasTreeEnEmpresa(lstCatsMontos, idEmpresa, obj.IdCategoria);
                if(obj.Hijos.Count() > 0)
                {
                    obj.Presupuesto = lstCatsMontos.Where(x => x.IdCategoriaPadre == obj.IdCategoria).Sum(x => x.Presupuesto);
                    lstCatsMontos.SingleOrDefault(x => x.IdCategoria == obj.IdCategoria).Presupuesto = obj.Presupuesto;
                }
            }

            return categoriasTree;
        }
开发者ID:EvertNube,项目名称:nbLibros,代码行数:29,代码来源:ReportesBL.cs

示例3: Initialize

        private static void Initialize(List<Node> nodes)
        {
            foreach (var node in nodes)
            {
                var left = nodes.SingleOrDefault(n => n.Y == node.Y && n.X == (node.X - 1));
                var right = nodes.SingleOrDefault(n => n.Y == node.Y && n.X == (node.X + 1));
                var up = nodes.SingleOrDefault(n => n.X == node.X && n.Y == (node.Y - 1));
                var down = nodes.SingleOrDefault(n => n.X == node.X && n.Y == (node.Y + 1));

                if (left != null) node.Reachable.Add(left);
                if (right != null) node.Reachable.Add(right);
                if (up != null) node.Reachable.Add(up);
                if (down != null) node.Reachable.Add(down);
            }
        }
开发者ID:TimBurga,项目名称:PathFinding,代码行数:15,代码来源:Grid.cs

示例4: GetFirstLevelDepartmentIdByDepartment

 public string[] GetFirstLevelDepartmentIdByDepartment(int departmentId)
 {
     string postString = string.Join("&", "url=http://service.dianping.com/ba/base/organizationalstructure/OrganizationService_1.0.0"
                                         , "method=getDepartmentHierarchy"
                                         , "parameterTypes=int"
                                         , "parameters=" + departmentId.ToString());
     byte[] postData = Encoding.UTF8.GetBytes(postString);
     List<Department> departmentList = new List<Department>();
     using (WebClient client = new WebClient())
     {
         client.Headers.Add("serialize", 7.ToString());
         client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
         byte[] responseData = client.UploadData(ORGANIZATIONAL_STRUCTURE_PIGEON, "POST", postData);//得到返回字符流
         string result = Encoding.UTF8.GetString(responseData);//解码
         departmentList = JsonConvert.DeserializeObject<List<Department>>(result);
     }
     if (departmentList == null)
     {
         return new List<string>().ToArray();
     }
     else
     {
         var firstLevelDepartment = departmentList.SingleOrDefault(_ => _.Level == 1);
         if (firstLevelDepartment == null)
         {
             return new List<string>().ToArray();
         }
         else
         {
             return new string[] { firstLevelDepartment.DepartmentId.ToString() };
         }
     }
 }
开发者ID:nanin,项目名称:k2-workflowapi,代码行数:33,代码来源:EmployeeServiceProvider.cs

示例5: RavenJToken_DeepEquals_Array_Test

        public void RavenJToken_DeepEquals_Array_Test()
        {
            var original = new {Tokens = new[] {"Token-1", "Token-2", "Token-3"}};
            var modified = new {Tokens = new[] {"Token-1", "Token-3"}};

            // In modified object we deleted one item "Token-2"

            var difference = new List<DocumentsChanges>();
            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modified), RavenJObject.FromObject(original), difference))
            {
                // OK
                // 1 difference - "Token-2" value removed
            }

            // Expecting one difference - "Token-2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                                 x.FieldOldValue == "Token-2") != null);

            var originalDoc = new Doc {Names = new List<PersonName> {new PersonName {Name = "Tom1"}, new PersonName {Name = "Tom2"}, new PersonName {Name = "Tom3"}}};
            var modifiedDoc = new Doc {Names = new List<PersonName> {new PersonName {Name = "Tom1"}, new PersonName {Name = "Tom3"}}};

            // In modified object we deleted one item "Tom2"

            difference = new List<DocumentsChanges>();
            if (!RavenJToken.DeepEquals(RavenJObject.FromObject(modifiedDoc), RavenJObject.FromObject(originalDoc), difference))
            {
                // SOMETHING WRONG?
                // 3 differences - "Tom1", "Tom2", "Tom3" objects removed
            }

            // Expecting one difference - "Tom2" ArrayValueRemoved
            Assert.True(difference.Count == 1 && difference.SingleOrDefault(x => x.Change == DocumentsChanges.ChangeType.ArrayValueRemoved &&
                                                                                 x.FieldOldValue == "{\r\n  \"Name\": \"Tom2\"\r\n}") != null);
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:34,代码来源:RavenDB_3042.cs

示例6: DistributeRemainingSpaceToElementsWithUndefinedWidth

        void DistributeRemainingSpaceToElementsWithUndefinedWidth(Unit lineWidth, List<LayoutedElement> elementsInLine)
        {
            var elementWithUndefinedWidth = elementsInLine.SingleOrDefault(x => !x.ForcedInnerWidth.IsDefined);
            if (elementWithUndefinedWidth != null)
            {
                var containerSpaceLeft = containerInnerWidth - lineWidth;
                if (containerSpaceLeft == 0.cm())
                    containerSpaceLeft = containerInnerWidth;

                elementWithUndefinedWidth.ForcedInnerWidth = containerSpaceLeft;
            }

            var left = Unit.Zero;
            var top = Unit.Zero;
            foreach (var layoutedElement in elementsInLine)
            {
                layoutedElement.Left = left;
                left += layoutedElement.OuterWidth;

                if (containerInnerHeight != 0.cm() && top + layoutedElement.OuterHeight > containerInnerHeight)
                    layoutedElement.ForcedOuterHeight = containerInnerHeight - top;

                top += layoutedElement.OuterHeight;
            }
        }
开发者ID:asgerhallas,项目名称:DomFx,代码行数:25,代码来源:LiningLayouter.cs

示例7: ApplyDeviceConfigurationModels

 public void ApplyDeviceConfigurationModels(List<DeviceConfiguration> deviceConfigurations, List<CoinConfiguration> coinConfigurations)
 {
     foreach (DeviceViewModel deviceViewModel in Devices)
     {
         DeviceConfiguration deviceConfiguration = deviceConfigurations.SingleOrDefault(dc => dc.Equals(deviceViewModel));
         if (deviceConfiguration != null)
         {
             deviceViewModel.Enabled = deviceConfiguration.Enabled;
             if (!String.IsNullOrEmpty(deviceConfiguration.CoinSymbol))
             {
                 CoinConfiguration coinConfiguration = coinConfigurations.SingleOrDefault(
                     cc => cc.Coin.Symbol.Equals(deviceConfiguration.CoinSymbol, StringComparison.OrdinalIgnoreCase));
                 if (coinConfiguration != null)
                     deviceViewModel.Coin = coinConfiguration.Coin;
             }
         }
         else
         {
             deviceViewModel.Enabled = true;
             CoinConfiguration coinConfiguration = coinConfigurations.SingleOrDefault(
                 cc => cc.Coin.Symbol.Equals("BTC", StringComparison.OrdinalIgnoreCase));
             if (coinConfiguration != null)
                 deviceViewModel.Coin = coinConfiguration.Coin;
         }
     }
 }
开发者ID:nvirus,项目名称:MultiMiner,代码行数:26,代码来源:MainFormViewModel.cs

示例8: Get

        public IEnumerable<ViewTopFiveVoters> Get(int Id)
        {
            List<ViewTopFiveVoters> voters = new List<ViewTopFiveVoters>();
            var output = from p in _db.VoteHistory
                         where p.ProposalId == Id
                         group p by p.UserId into g

                         select new { UserId = g.Key, NoVote = g.Count() };

            var output2 = output.OrderByDescending(c => c.NoVote).Take(5).ToList();
               int Rank = 1;
            foreach (var item in output2)
            {
                Models.User user = _db.User.FirstOrDefault(c=>c.UserId == item.UserId);

                voters.Add(new ViewTopFiveVoters { Id = item.UserId, Email = user.Email, Image = user.Image, Name = user.Name, Rank = Rank++ });
            }
            var allvoters = output.OrderByDescending(c=>c.NoVote).ToList();
            int CurentRank = allvoters.AsQueryable().Select((user, index) => new { user.UserId, index }).Where(user => user.UserId == WebSecurity.CurrentUserId).Select(c=>c.index).FirstOrDefault();//finding ranking number
            CurentRank++;
            ViewTopFiveVoters check = voters.SingleOrDefault(c => c.Id == WebSecurity.CurrentUserId);

            if (CurentRank >= 5 && check == null)
            {
                voters.RemoveAt(4);
                Models.User me = _db.User.FirstOrDefault(c=>c.UserId == WebSecurity.CurrentUserId);
                voters.Insert(4, new ViewTopFiveVoters { Id = WebSecurity.CurrentUserId, Rank = CurentRank, Email = me.Email, Image = me.Image, Name = me.Name });
            }

            return voters;
        }
开发者ID:msanj1,项目名称:BOTF,代码行数:31,代码来源:ProposalsController.cs

示例9: Main

        public static void Main(string[] args)
        {
            try
            {
            #if DEBUG
                //args = new string[] { "-o=unmount", @"-p=C:\Virtual Hard Disks\example.vhd" };
            #endif

                var helpOptions = new HelpOptions();

                var options = new List<IExecutable>() {
                    { helpOptions },
                    { new MountOptions() }
                };

                helpOptions.Parent = options;

                options.SingleOrDefault(option => option.Execute(args));

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(1);
            }
        }
开发者ID:hubkey,项目名称:VHD,代码行数:26,代码来源:Program.cs

示例10: GetMasterDetailsViewModels

        public IEnumerable<MasterDetailsViewModel> GetMasterDetailsViewModels()
        {
            List<MasterDetailsViewModel> masterDetailsViewModelList;

            var categoryViewModels = new List<CategoryViewModel>
                            {
                                new CategoryViewModel { CategoryId=1, CategoryName = "Fruit"},
                                new CategoryViewModel {CategoryId=2, CategoryName = "Car"},
                                new CategoryViewModel {CategoryId=3, CategoryName = "Cloth"},
                            };

            // Create some products.
            var productViewModels = new List<ProductViewModel>
                        {
                            new ProductViewModel {ProductId=1, ProductName="Apple", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=2, ProductName="Mango", ProductPrice=20, CategoryId=1},
                            new ProductViewModel {ProductId=3, ProductName="Orange", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=4, ProductName="Banana", ProductPrice=20, CategoryId=1},
                            new ProductViewModel {ProductId=5, ProductName="Licho", ProductPrice=15, CategoryId=1},
                            new ProductViewModel {ProductId=6, ProductName="Jack Fruit", ProductPrice=20, CategoryId=1},

                            new ProductViewModel {ProductId=7, ProductName="Toyota", ProductPrice=15000, CategoryId=2},
                            new ProductViewModel {ProductId=8, ProductName="Nissan", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=9, ProductName="Tata", ProductPrice=50000, CategoryId=2},
                            new ProductViewModel {ProductId=10, ProductName="Honda", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=11, ProductName="Kimi", ProductPrice=50000, CategoryId=2},
                            new ProductViewModel {ProductId=12, ProductName="Suzuki", ProductPrice=20000, CategoryId=2},
                            new ProductViewModel {ProductId=13, ProductName="Ferrari", ProductPrice=50000, CategoryId=2},

                            new ProductViewModel {ProductId=14, ProductName="T Shirt", ProductPrice=20000, CategoryId=3},
                            new ProductViewModel {ProductId=15, ProductName="Polo Shirt", ProductPrice=50000, CategoryId=3},
                            new ProductViewModel {ProductId=16, ProductName="Shirt", ProductPrice=200, CategoryId=3},
                            new ProductViewModel {ProductId=17, ProductName="Panjabi", ProductPrice=500, CategoryId=3},
                            new ProductViewModel {ProductId=18, ProductName="Fotuya", ProductPrice=200, CategoryId=3},
                            new ProductViewModel {ProductId=19, ProductName="Shari", ProductPrice=500, CategoryId=3},
                            new ProductViewModel {ProductId=20, ProductName="Kamij", ProductPrice=400, CategoryId=3},

                        };

            var masterDetailsViewModels =
                productViewModels.Select(
                    x =>
                        {
                            var categoryViewModel = categoryViewModels.SingleOrDefault(c => c.CategoryId == x.CategoryId);
                            return categoryViewModel != null ? new MasterDetailsViewModel()
                                                                    {
                                                                        ProductId = x.ProductId,
                                                                        ProductName = x.ProductName,
                                                                        ProductPrice = x.ProductPrice,
                                                                        CategoryId = x.CategoryId,
                                                                        CategoryName =
                                                                            categoryViewModel.CategoryName
                                                                    } : null;
                        }).ToList
                    ();

            masterDetailsViewModelList = masterDetailsViewModels;

            return masterDetailsViewModelList.AsQueryable();
        }
开发者ID:raselahmmedgit,项目名称:report-sample,代码行数:60,代码来源:MasterDetailsReportService.cs

示例11: ApplyDeviceConfigurationModels

 public void ApplyDeviceConfigurationModels(List<Engine.Data.Configuration.Device> deviceConfigurations, List<Engine.Data.Configuration.Coin> coinConfigurations)
 {
     foreach (DeviceViewModel deviceViewModel in Devices)
     {
         Engine.Data.Configuration.Device deviceConfiguration = deviceConfigurations.SingleOrDefault(dc => dc.Equals(deviceViewModel));
         if (deviceConfiguration != null)
         {
             deviceViewModel.Enabled = deviceConfiguration.Enabled;
             if (String.IsNullOrEmpty(deviceConfiguration.CoinSymbol))
             {
                 deviceViewModel.Coin = null;
             }
             else
             {
                 Engine.Data.Configuration.Coin coinConfiguration = coinConfigurations.SingleOrDefault(
                     cc => cc.CryptoCoin.Symbol.Equals(deviceConfiguration.CoinSymbol, StringComparison.OrdinalIgnoreCase));
                 if (coinConfiguration != null)
                     deviceViewModel.Coin = coinConfiguration.CryptoCoin;
             }
         }
         else
         {
             deviceViewModel.Enabled = true;
             Engine.Data.Configuration.Coin coinConfiguration = coinConfigurations.SingleOrDefault(
                 cc => cc.CryptoCoin.Symbol.Equals(KnownCoins.BitcoinSymbol, StringComparison.OrdinalIgnoreCase));
             if (coinConfiguration != null)
                 deviceViewModel.Coin = coinConfiguration.CryptoCoin;
         }
     }
 }
开发者ID:Tradingangel,项目名称:MultiMiner,代码行数:30,代码来源:MinerFormViewModel.cs

示例12: ParseString

		public virtual List<CSClass> ParseString(string data, string filePath, string projectDirectory, IEnumerable<CSClass> existingClassList)
		{
			string relativeFilePath = filePath.Replace(projectDirectory,"");
			if(relativeFilePath.StartsWith("\\"))
			{
				relativeFilePath = relativeFilePath.Substring(1);
			}
			List<CSClass> returnValue = new List<CSClass>(existingClassList ?? new CSClass[]{} );
			var parser = new CSharpParser();
			var compilationUnit = parser.Parse(data, filePath);
			var namespaceNodeList = compilationUnit.Children.Where(i=>i is NamespaceDeclaration);
			foreach(NamespaceDeclaration namespaceNode in namespaceNodeList)
			{
				var typeDeclarationNodeList = namespaceNode.Children.Where(i=>i is TypeDeclaration);
				foreach(TypeDeclaration typeDeclarationNode in typeDeclarationNodeList)
				{
					var classObject = returnValue.SingleOrDefault(i=>i.ClassName == typeDeclarationNode.Name && i.NamespaceName == namespaceNode.FullName);
					if(classObject == null)
					{
						classObject = new CSClass
						{
							NamespaceName = namespaceNode.FullName,
							ClassName = typeDeclarationNode.Name
						};
						returnValue.Add(classObject);
					}
					ClassParser.BuildClass(classObject, typeDeclarationNode, relativeFilePath);
				}
			}
			return returnValue;
		}
开发者ID:mmooney,项目名称:MMDB.UITest,代码行数:31,代码来源:ClassParser.cs

示例13: CreateCodeReviewResponse

		internal static ShimWorkItem CreateCodeReviewResponse(int id, string state, string reviewResult)
		{
			var responseFields = new List<Field>()
				{
					new ShimField()
					{ 
						NameGet = () => CodeReviewPolicy.ClosedStatus,
						ValueGet = () => reviewResult
					}
				};
			var fakeResponseFields = new ShimFieldCollection()
			{
				ItemGetString = (s) => responseFields.SingleOrDefault(f => f.Name == s)
			};

			var responseWorkItem = new ShimWorkItem()
			{
				TypeGet = () => new ShimWorkItemType()
				{
					NameGet = () => "Code Review Response"
				},
				IdGet = () => id,
				StateGet = () => state,
				FieldsGet = () => fakeResponseFields,
			};
			return responseWorkItem;
		}
开发者ID:aheubusch,项目名称:ColinsALMCornerCheckinPolicies,代码行数:27,代码来源:FakeUtils.cs

示例14: ParseDeducciones

        public void ParseDeducciones(List<Empleado> employees)
        {
            Deduccion deduccion;
            IRow currentRow;
            ISheet sheet = workBook.GetSheetAt(ExcelReader.DeduccionesSheet);

            IEnumerator rowEnumator = sheet.GetRowEnumerator();

            //Ignore headers
            rowEnumator.MoveNext();

            Empleado employee;

            while (rowEnumator.MoveNext())
            {

                currentRow = rowEnumator.Current as IRow;
                deduccion = deduccionParser.Parse(currentRow);

                if (deduccion.NumEmpleado.HasValue)
                {
                    employee = employees.SingleOrDefault(emp => emp.Numero == deduccion.NumEmpleado.Value);
                    if (employee != null)
                        employee.ParsedDeducciones.Add(deduccion);
                }

            }
        }
开发者ID:Wirwing,项目名称:SNCFDI,代码行数:28,代码来源:ExcelReader.cs

示例15: GetCorrespondingField

        public Field GetCorrespondingField(string destinationFieldName, List<FieldMappingConfiguration> mappingConfigs)
        {
            Field sourceField;
            if (mappingConfigs != null)
            {
                var mappingConfig = mappingConfigs.SingleOrDefault(m => m.DestinationFieldName.Equals(destinationFieldName, StringComparison.InvariantCultureIgnoreCase));
                if (mappingConfig != null)
                {
                    string mapSourceFieldName = mappingConfig.SourceFieldName != null ? mappingConfig.SourceFieldName : destinationFieldName;
                    sourceField = GetField(mapSourceFieldName);
                }
                else
                {
                    string mapSourceFieldName = destinationFieldName;
                    sourceField = GetField(mapSourceFieldName);
                }
            }
            else
            {
                string mapSourceFieldName = destinationFieldName;
                sourceField = GetField(mapSourceFieldName);
            }

            return sourceField;
        }
开发者ID:khangtran-steadfast,项目名称:DatabaseMigration,代码行数:25,代码来源:SourceTable.cs


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