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


C# List.SingleOrDefault方法代码示例

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


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

示例1: ShouldBeAbleToBroadcastMessagesAndReceiveResponses

        public void ShouldBeAbleToBroadcastMessagesAndReceiveResponses()
        {
            var sampleClusterConfiguration = BuildSampleClusterConfiguration();

            var testServer1 = SetupTestServerForNode(sampleClusterConfiguration.Nodes[0]);
            testServer1.Start();

            var testServer2 = SetupTestServerForNode(sampleClusterConfiguration.Nodes[1]);
            testServer2.Start();

            var sut = new NetMqRpcChannel(sampleClusterConfiguration, TimeSpan.FromMilliseconds(200));

            var sampleRequest = new SampleRequest("test");

            var autoResetEvent = new AutoResetEvent(false);

            int expectedNumberOfResponses = sampleClusterConfiguration.Nodes.Length;
            var responses = new List<SampleResponse>();

            sut.Broadcast<SampleRequest, SampleResponse>(sampleRequest, response =>
            {
                responses.Add(response);

                if (responses.Count >= expectedNumberOfResponses)
                {
                    autoResetEvent.Set();
                }
            });

            autoResetEvent.WaitOne(TimeSpan.FromSeconds(1));

            Assert.AreEqual(expectedNumberOfResponses, responses.Count);
            Assert.IsNotNull(responses.SingleOrDefault(x => x.ResponseString == sampleClusterConfiguration.Nodes[0].Id.ToString()));
            Assert.IsNotNull(responses.SingleOrDefault(x => x.ResponseString == sampleClusterConfiguration.Nodes[1].Id.ToString()));
        }
开发者ID:DannyRyman,项目名称:DistributedStateEngine_Old,代码行数:35,代码来源:NetMQRpcChannelFixtures.cs

示例2: when_processing_batches

        public void when_processing_batches()
        {
            var orders = Enumerable.Range(1, 20).Select(x => new Order {Id = x}).ToList();

            var batches = new List<List<Order>>();

            Action<List<Order>> action = batches.Add;

            var orderBatcher = new OrderBatcher();
            orderBatcher.ProcessBatches(orders, action);

            Assert.That(batches.Count, Is.EqualTo(4), "It should have processed the orders in 4 batches");

            Assert.That(batches.SingleOrDefault(x => x.First().Id == 1 && x.Last().Id == 5), Is.Not.Null, "It should have processed the 1st batch");
            Assert.That(batches.SingleOrDefault(x => x.First().Id == 6 && x.Last().Id == 10), Is.Not.Null, "It should have processed the 2nd batch");
            Assert.That(batches.SingleOrDefault(x => x.First().Id == 11 && x.Last().Id == 15), Is.Not.Null, "It should have processed the 3rd batch");
            Assert.That(batches.SingleOrDefault(x => x.First().Id == 16 && x.Last().Id == 20), Is.Not.Null, "It should have processed the 4th batch");
        }
开发者ID:odw1,项目名称:Blog,代码行数:18,代码来源:OrderBatcherTests.cs

示例3: AreEqual

 public static void AreEqual(XmlNodeList tlgNodes, string currentPath, List<OperationData> operationData)
 {
     Assert.AreEqual(tlgNodes.Count, operationData.Count);
     for (int i = 0; i < tlgNodes.Count; i++)
     {
         var matchingOperationData = operationData.SingleOrDefault(x => x.Id.FindIsoId() == tlgNodes[i].Attributes["A"].Value);
         AreEqual(tlgNodes[i], currentPath, matchingOperationData);
     }
 }
开发者ID:ADAPT,项目名称:ISOv4Plugin,代码行数:9,代码来源:OperationDataAssert.cs

示例4: AssertEnvironmentConfigurationList

 private void AssertEnvironmentConfigurationList(List<DeployEnvironmentConfiguration> expectedList, List<DeployEnvironmentConfiguration> actualList)
 {
     expectedList = (expectedList ?? new List<DeployEnvironmentConfiguration>());
     actualList = (actualList ?? new List<DeployEnvironmentConfiguration>());
     Assert.AreEqual(expectedList.Count(), actualList.Count);
     foreach (var expectedItem in expectedList)
     {
         var actualItem = actualList.SingleOrDefault(i => i.ParentId == expectedItem.ParentId);
         AssertEnvironmentConfiguration(expectedItem, actualItem);
     }
 }
开发者ID:gsbastian,项目名称:Sriracha.Deploy,代码行数:11,代码来源:ProjectRepositoryEnvironmentTests.cs

示例5: CheckIndex

 static void CheckIndex(TestDb db, List<IndexInfo> indexes, string iname, bool unique, params string [] columns)
 {
     if (columns == null)
         throw new Exception ("Don't!");
     var idx = indexes.SingleOrDefault (i => i.name == iname);
     Assert.IsNotNull (idx, String.Format ("Index {0} not found", iname));
     Assert.AreEqual (idx.unique, unique, String.Format ("Index {0} unique expected {1} but got {2}", iname, unique, idx.unique));
     var idx_columns = db.Query<IndexColumns> (String.Format ("PRAGMA INDEX_INFO (\"{0}\")", iname));
     Assert.AreEqual (columns.Length, idx_columns.Count, String.Format ("# of columns: expected {0}, got {1}", columns.Length, idx_columns.Count));
     foreach (var col in columns) {
         Assert.IsNotNull (idx_columns.SingleOrDefault (c => c.name == col), String.Format ("Column {0} not in index {1}", col, idx.name));
     }
 }
开发者ID:Toshik,项目名称:sqlite-net,代码行数:13,代码来源:UniqueTest.cs

示例6: AreEqual

        public static void AreEqual(XmlNodeList tskNodes, string currentPath, List<LoggedData> loggedData, Catalog catalog)
        {
            int tsksWithTlgs = 0;
            foreach (XmlNode node in tskNodes)
            {
                if (node.SelectNodes("TLG").Count > 0)
                {
                    tsksWithTlgs++;

                    var matchingLoggedData = loggedData.SingleOrDefault(x => x.Id.FindIsoId() == node.Attributes["A"].Value);
                    AreEqual(node, currentPath, matchingLoggedData, catalog);
                }
            }

            Assert.AreEqual(tsksWithTlgs, loggedData.Count);
        }
开发者ID:ADAPT,项目名称:ISOv4Plugin,代码行数:16,代码来源:LoggedDataAssert.cs

示例7: SetUp

        public void SetUp()
        {
            _collectionWrapper = Substitute.For<ICollectionWrapper<StreamReadModel, Int64>>();
            rmStream = new List<StreamReadModel>();
            rmDocuments = new List<DocumentDescriptorReadModel>();

            _collectionWrapper.When(r => r.Insert(
                Arg.Any<DomainEvent>(),
                Arg.Any<StreamReadModel>()))
                .Do(cinfo => rmStream.Add((StreamReadModel)cinfo.Args()[1]));
            _collectionWrapper.All.Returns(rmStream.AsQueryable());

            _readerDocumentReadModel = Substitute.For<IReader<DocumentDescriptorReadModel, DocumentDescriptorId>>();
            _readerDocumentReadModel.AllUnsorted.Returns(rmDocuments.AsQueryable());
            _readerDocumentReadModel.AllSortedById.Returns(rmDocuments.AsQueryable().OrderBy(r => r.Id));
            _readerDocumentReadModel.FindOneById(Arg.Any<DocumentDescriptorId>())
                .Returns(cinfo => rmDocuments.SingleOrDefault(d => d.Id == (DocumentDescriptorId)cinfo.Args()[0]));

            _handleWriter = Substitute.For<IDocumentWriter>();
            _blobStore = Substitute.For<IBlobStore>();
        }
开发者ID:ProximoSrl,项目名称:Jarvis.DocumentStore,代码行数:21,代码来源:StreamProjectionTest.cs

示例8: AssertFileContentIsCorrect

        internal static void AssertFileContentIsCorrect(string file, string repositoryName, List<RequestEntityImp> allRequests = null)
        {
            var document = new XmlDocument();
            document.Load(file);

            var documentElement = document.DocumentElement;
            Assert.That(documentElement, Is.Not.Null);

            // ReSharper disable PossibleNullReferenceException
            var documentName = documentElement.GetAttribute("Name");
            // ReSharper restore PossibleNullReferenceException

            Assert.That(documentName, Is.EqualTo(repositoryName));

            var requestsElement = documentElement.SelectSingleNode("Requests");
            Assert.That(requestsElement, Is.Not.Null);

            if (allRequests != null)
            {
            // ReSharper disable PossibleNullReferenceException
                Assert.That(requestsElement.ChildNodes.Count, Is.EqualTo(allRequests.Count));

                foreach (XmlElement requestElement in requestsElement.ChildNodes)
                {
                    var id = requestElement.GetAttribute("Id");
                    Assert.That(id, Is.Not.Null.Or.Empty);

                    Assert.That(allRequests.SingleOrDefault(r => r.PersistentId == id), Is.Not.Null);
                }
            // ReSharper restore PossibleNullReferenceException
            }
        }
开发者ID:danbra,项目名称:MoneyManager,代码行数:32,代码来源:RepositoryStateTests.cs

示例9: Run_SupplySettingToDeleteFromTargetFolder_AllFilesAreDeleted

        public void Run_SupplySettingToDeleteFromTargetFolder_AllFilesAreDeleted()
        {
            // arrange
            _settings = new RandomizerWorkerSettings
            {
                DeleteFromTargetFolder = true,
                PathTo = "path to"
            };

            List<AppFile> files = new List<AppFile>
            {
                new AppFile { },
                new AppFile { },
                new AppFile { }
            };

            _fileServiceMock.Setup(x => x.GetFiles(_settings.PathTo)).Returns(files);

            _fileServiceMock
                .Setup(x => x.DeleteFile(It.IsAny<AppFile>()))
                .Callback((AppFile file) =>
                {
                    Assert.That(file, Is.EqualTo(files.SingleOrDefault(x => x == file)));
                });

            // act, assert
            _worker.Run(_settings, (x) => { }, (y) => { }, () => { });

            _backgroundWorkerMock.Raise(x => { x.OnDoWork += null; }, null, new System.ComponentModel.DoWorkEventArgs(null));
        }
开发者ID:desperate-man,项目名称:FileRandomizer3000,代码行数:30,代码来源:RandomizerWorkerTests.cs

示例10: atualizar_estrutura_hospitalar_departamentoExistentes


//.........这里部分代码省略.........

                if (listaContas.All(c => c.CodigoDaConta != codigoDeConta))
                {
                    if (conta == null)
                    {
                        throw new Exception();

                        conta = new Conta(descricaoDaConta, tipoContaOutras)
                        {
                            CodigoDaConta = codigoDeConta
                        };
                        repositorioContas.Salvar(conta);
                    }

                    listaContas.Add(conta);
                }
                else
                    conta = listaContas.FirstOrDefault(c => c.CodigoDaConta == codigoDeConta);

            }
            var grupos = new GruposDeConta();
            var gruposDeContaLista = new List<GrupoDeConta>();
            foreach (var grupo in gruposDeConta)
            {
                var grupoDeConta = grupos.ObterPor(grupo);

                if (grupoDeConta == null)
                    throw new Exception();

                var contasDoGrupo = documento.Where(x => x.GrupoResumoNome == grupo).Select(y => y.CodigoConta).Distinct();

                foreach (var codigoConta in contasDoGrupo)
                {
                    var conta = listaContas.FirstOrDefault(c => c.CodigoDaConta == codigoConta);

                    if (grupoDeConta.Contas == null)
                        grupoDeConta.Contas = new List<Conta>();

                    if (grupoDeConta.Contas.All(c => c.CodigoDaConta != codigoConta))
                        grupoDeConta.Adicionar(conta);
                }

                gruposDeContaLista.Add(grupoDeConta);
                grupos.Salvar(grupoDeConta);
            }

            var codigosDecentrosDeCusto = documento.Select(x => x.CodigoCentroDeCusto).Distinct();

            foreach (var codigoDeCentro in codigosDecentrosDeCusto)
            {
                var descricaoDeCentroDeCusto = documento.Where(x => x.CodigoCentroDeCusto == codigoDeCentro).Select(y => y.DescricaoCentroDeCusto).Distinct().First();

                var centroDeCusto = repositorioDeCusto.ObterPor(codigoDeCentro);
                if (centroDeCusto == null)
                {
                        throw new Exception();

                    centroDeCusto = new CentroDeCusto(descricaoDeCentroDeCusto)
                    {
                        CodigoDoCentroDeCusto = codigoDeCentro
                    };
                }

                var contas = documento.Where(x => x.CodigoCentroDeCusto == codigoDeCentro).Select(y => y.CodigoConta).Distinct();

                if (centroDeCusto.Contas == null)
                    centroDeCusto.Contas = new List<Conta>();

                foreach (var conta in contas)
                {
                    if (centroDeCusto.Contas.All(c => c.CodigoDaConta != conta))
                        centroDeCusto.AdicionarConta(listaContas.SingleOrDefault(x => x.CodigoDaConta == conta));
                }

                repositorioDeCusto.Salvar(centroDeCusto);
                listaCentrosDeCusto.Add(centroDeCusto);
            }

            var hospitais = documento.Select(x => x.NomeHospital).Distinct();

            foreach (var nomeHospital in hospitais)
            {
                var hospital = repositorioDeHospitais.ObterPor(nomeHospital);
                if(hospital == null)
                    throw new Exception();

                var centrosDeCusto = documento.Where(x => x.NomeHospital == hospital.Nome).Select(y => y.CodigoCentroDeCusto).Distinct();

                if (hospital.CentrosDeCusto == null)
                    hospital.CentrosDeCusto = new List<CentroDeCusto>();

                foreach (var codigoCentroCusto in centrosDeCusto)
                {
                    if (hospital.CentrosDeCusto.All(c => c.CodigoDoCentroDeCusto != codigoCentroCusto))
                        hospital.AdicionarCentroDeCusto(listaCentrosDeCusto.SingleOrDefault(x => x.CodigoDoCentroDeCusto == codigoCentroCusto));
                }

                repositorioDeHospitais.Salvar(hospital);
            }
        }
开发者ID:GersonAlves,项目名称:Orcamento2015,代码行数:101,代码来源:AtualizarDepartamentoCentroDeCustoEConta.cs

示例11: VerifyInvoiceItemsAreEqual

        private void VerifyInvoiceItemsAreEqual(string layout, List<InvoiceTransactionLineItem> list1, List<InvoiceTransactionLineItem> list2)
        {
            if (list1 == null || list2 == null)
            {
                Assert.IsTrue(list1 == null && list2 == null, "One list is NULL and the other is not. Expected both to be NULL");
                return;
            }

            Assert.AreEqual(list1.Count, list2.Count, "Number of items are different");

            if (layout == "S")
            {
                foreach (var item in list1)
                {
                    var itemInList2 = list2.SingleOrDefault(i => i.Description == item.Description &&
                        i.AccountId == item.AccountId &&
                        i.TaxCode == item.TaxCode
                        );

                    Assert.IsNotNull(itemInList2, "Service item differs in first list");
                }

                foreach (var item in list2)
                {
                    var itemInList1 = list1.SingleOrDefault(i => i.Description == item.Description &&
                        i.AccountId == item.AccountId &&
                        i.TaxCode == item.TaxCode
                        );

                    Assert.IsNotNull(itemInList1, "Service item differs in second list");
                }
            }
            else
            {
                foreach (var item in list1)
                {
                    var itemInList2 = list2.SingleOrDefault(i => i.Description == item.Description &&
                        i.AccountId == item.AccountId &&
                        i.TaxCode == item.TaxCode &&
                        i.Quantity == item.Quantity &&
                        i.UnitPrice == item.UnitPrice &&
                        i.PercentageDiscount == item.PercentageDiscount &&
                        i.InventoryId == item.InventoryId
                        );

                    Assert.IsNotNull(itemInList2, "Line item differs in first list");
                }

                foreach (var item in list2)
                {
                    var itemInList1 = list1.SingleOrDefault(i => i.Description == item.Description &&
                            i.AccountId == item.AccountId &&
                        i.TaxCode == item.TaxCode &&
                        i.Quantity == item.Quantity &&
                        i.UnitPrice == item.UnitPrice &&
                        i.PercentageDiscount == item.PercentageDiscount &&
                        i.InventoryId == item.InventoryId
                        );

                    Assert.IsNotNull(itemInList1, "Line item differs in second list");
                }
            }
        }
开发者ID:rizcreature,项目名称:api-sdk-dotnet,代码行数:63,代码来源:InvoiceTests.cs

示例12: VerifyInvoiceAttachmentsAreEqual

        private void VerifyInvoiceAttachmentsAreEqual(List<FileAttachmentInfo> list1, List<FileAttachmentInfo> list2)
        {
            if (list1 == null || list2 == null || list1.Count == 0 || list2.Count == 0)
            {
                //this is because an insert may have sent attachments as null but a GET will return them as empy list.
                Assert.IsTrue(list1 == null || list1.Count == 0, "Expected no items but list1 had some");
                Assert.IsTrue(list2 == null || list2.Count == 0, "Expected no items but list2 had some");
                return;
            }

            foreach (var detail in list1)
            {
                var detailInList2 = list2.SingleOrDefault(d => d.Id == detail.Id && d.Name == detail.Name && d.Description == detail.Description);
                Assert.IsNotNull(detailInList2, "Attachments do not match");
            }

            foreach (var detail in list2)
            {
                var detailInList1 = list1.SingleOrDefault(d => d.Id == detail.Id && d.Name == detail.Name && d.Description == detail.Description);
                Assert.IsNotNull(detailInList1, "Attachments do not match");
            }
        }
开发者ID:rizcreature,项目名称:api-sdk-dotnet,代码行数:22,代码来源:InvoiceTests.cs

示例13: ListExtensions_SingleOrDefault_ThrowsExceptionIfListHasMultipleItems

        public void ListExtensions_SingleOrDefault_ThrowsExceptionIfListHasMultipleItems()
        {
            var list = new List<Int32>() { 1, 2 };

            Assert.That(() => list.SingleOrDefault(),
                Throws.TypeOf<InvalidOperationException>());
        }
开发者ID:RUSshy,项目名称:ultraviolet,代码行数:7,代码来源:ListExtensionsTest.cs

示例14: ListExtensions_SingleOrDefault_ReturnsSingleItemInList

        public void ListExtensions_SingleOrDefault_ReturnsSingleItemInList()
        {
            var list = new List<Int32>() { 4 };

            var result = list.SingleOrDefault();

            TheResultingValue(result).ShouldBe(4);
        }
开发者ID:RUSshy,项目名称:ultraviolet,代码行数:8,代码来源:ListExtensionsTest.cs

示例15: ListExtensions_SingleOrDefault_ReturnsDefaultValueIfListIsEmpty

        public void ListExtensions_SingleOrDefault_ReturnsDefaultValueIfListIsEmpty()
        {
            var list = new List<Int32>();

            var result = list.SingleOrDefault();

            TheResultingValue(result).ShouldBe(default(Int32));
        }
开发者ID:RUSshy,项目名称:ultraviolet,代码行数:8,代码来源:ListExtensionsTest.cs


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