本文整理汇总了C#中NUnit.Framework.List.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# List.GroupBy方法的具体用法?C# List.GroupBy怎么用?C# List.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NUnit.Framework.List
的用法示例。
在下文中一共展示了List.GroupBy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ChangesToSourceAreIgnoredInWhileIteratingOverResultsAfterFirstElementRetrieved
public void ChangesToSourceAreIgnoredInWhileIteratingOverResultsAfterFirstElementRetrieved()
{
var source = new List<string> { "a", "b", "c", "def" };
var groups = source.GroupBy(x => x.Length);
using (var iterator = groups.GetEnumerator())
{
Assert.IsTrue(iterator.MoveNext());
iterator.Current.AssertSequenceEqual("a", "b", "c");
// If GroupBy still needed to iterate over the source, this would cause a
// InvalidOperationException when we next fetched an element from groups.
source.Add("ghi");
Assert.IsTrue(iterator.MoveNext());
// ghi isn't in the group
iterator.Current.AssertSequenceEqual("def");
Assert.IsFalse(iterator.MoveNext());
}
// If we iterate again now - without calling GroupBy again - we'll see the difference:
using (var iterator = groups.GetEnumerator())
{
Assert.IsTrue(iterator.MoveNext());
iterator.Current.AssertSequenceEqual("a", "b", "c");
Assert.IsTrue(iterator.MoveNext());
iterator.Current.AssertSequenceEqual("def", "ghi");
}
}
示例2: CompareSolves
public void CompareSolves()
{
var groupBy = GetSolves().ToArray();
var bests = new List<Tuple<string, int>>();
foreach (var result in groupBy)
{
var grouByName = result.GroupBy(r => r.Item1);
Console.WriteLine("Problem" + result.Key);
var solves = grouByName.OrderByDescending(r => r.Sum(k => k.Item4));
var bsolves = solves.Where(s => s.Sum(r => r.Item4) == solves.First().Sum(r => r.Item4));
foreach (var bsolve in bsolves)
bests.Add(Tuple.Create(bsolve.Key, int.Parse(result.Key)));
foreach (var res in solves)
{
Console.WriteLine("{0}: {1}", res.Key, res.Sum(K => K.Item4) / res.Count());
}
foreach (var byS in result.GroupBy(r => r.Item3))
{
Console.WriteLine("Seed {0}", byS.Key);
foreach (var oneItem in byS.OrderByDescending(b => b.Item4))
{
Console.WriteLine("{0}: {1}", oneItem.Item1, oneItem.Item4);
}
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Who's BEST?");
foreach (var taskresult in bests.GroupBy(b => b.Item1).OrderByDescending(b => b.Count()))
{
Console.WriteLine("{0}: {1}% ({2})", taskresult.Key, taskresult.Count() * 100 / groupBy.Count(), string.Join(".", taskresult.Take(15).Select(b => b.Item2)));
}
}
示例3: should_generate_unique_ids
public void should_generate_unique_ids()
{
var messageIds = new List<MessageId>(200000);
for (var i = 0; i < messageIds.Capacity; ++i)
{
messageIds.Add(MessageId.NextId());
}
var duplicatedMessageIds = messageIds.GroupBy(x => x.Value).Where(x => x.Count() != 1).ToList();
duplicatedMessageIds.ShouldBeEmpty();
}
示例4: MeasureUpdatePerformance
public void MeasureUpdatePerformance()
{
var subscriptions = new List<Subscription>();
for (var typeIdIndex = 0; typeIdIndex < 20; ++typeIdIndex)
{
var typeId = new MessageTypeId("Abc.Foo.Events.FakeEvent" + typeIdIndex);
for (var routingIndex = 0; routingIndex < 500; ++routingIndex)
{
subscriptions.Add(new Subscription(typeId, new BindingKey(routingIndex.ToString())));
}
}
var subscriptionsByTypeId = subscriptions.GroupBy(x => x.MessageTypeId).ToDictionary(x => x.Key, x => x.Select(s=>s.BindingKey).ToArray());
_directory = new PeerDirectoryClient(_configurationMock.Object);
_directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(false)));
Console.WriteLine("Snapshot updates (add)");
using (Measure.Throughput(subscriptions.Count))
{
for (var subscriptionCount = 1; subscriptionCount <= subscriptions.Count; ++subscriptionCount)
{
_directory.Handle(new PeerSubscriptionsUpdated(_otherPeer.ToPeerDescriptor(false, subscriptions.Take(subscriptionCount))));
}
}
Console.WriteLine("Snapshot updates (remove)");
using (Measure.Throughput(subscriptions.Count))
{
for (var subscriptionCount = subscriptions.Count; subscriptionCount >= 1; --subscriptionCount)
{
_directory.Handle(new PeerSubscriptionsUpdated(_otherPeer.ToPeerDescriptor(false, subscriptions.Take(subscriptionCount))));
}
}
_directory = new PeerDirectoryClient(_configurationMock.Object);
_directory.Handle(new PeerStarted(_otherPeer.ToPeerDescriptor(false)));
Console.WriteLine("Snapshot updates per message type id (add)");
using (Measure.Throughput(subscriptions.Count))
{
foreach (var subscriptionGroup in subscriptionsByTypeId)
{
_directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.UtcNow, subscriptionGroup.Key, subscriptionGroup.Value));
}
}
Console.WriteLine("Snapshot updates per message type id (remove)");
using (Measure.Throughput(subscriptions.Count))
{
foreach (var subscriptionGroup in subscriptionsByTypeId)
{
_directory.Handle(new PeerSubscriptionsForTypesUpdated(_otherPeer.Id, DateTime.UtcNow, subscriptionGroup.Key));
}
}
}
示例5: GenerateMultipleIteratively
public void GenerateMultipleIteratively()
{
var gen = new Generator();
var stringList = new List<string>();
for (int i = 0; i < 100000; i++)
{
stringList.Add(gen.Single(9));
}
Assert.LessOrEqual(1, stringList.GroupBy(x => x).Count());
}
示例6: Method_Scenario_Result
public void Method_Scenario_Result()
{
var list = new List<string> {"hello", "world"};
var s = list[0];
Console.WriteLine(s);
Interlocked.Increment(ref _x2);
var dictionary = new Dictionary<int, string> {{0, "Hello"}, {2, "World"}};
var s1 = dictionary[0];
var dateTime = new DateTime(1988,10,10);
var dateTimes = new List<DateTime> { new DateTime(1988, 10, 10), new DateTime(1988, 10, 10), new DateTime(1987, 12, 29) };
var enumerable = from time in dateTimes group time by time.Date into grouping select new {Date = grouping, Count = grouping.Count()};
var enumerable2 = dateTimes.GroupBy(x => x.Date).Select(y => new {Date = y, Count = y.Count()}).ToList();
Console.WriteLine(s1);
}
示例7: GroupingElection
public void GroupingElection()
{
var election2015 = new List<Election>
{
new Election { Name = "Clinton", Votes = 8 },
new Election { Name = "Gore", Votes = 4 },
new Election { Name = "Bush", Votes = 1 },
new Election { Name = "Obama", Votes = 4 }
};
var groups = election2015.GroupBy(x => x.Votes, x => x.Name);
groups.ToList().ForEach(voteGroup =>
{
Console.WriteLine(voteGroup.Key);
foreach (var candidate in voteGroup)
{
Console.WriteLine(candidate);
}
});
}
示例8: GroupByList_v1
public void GroupByList_v1()
{
List<Pet> pets =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 },
new Pet { Name="Daisy", Age=4 } };
IEnumerable<IGrouping<int, string>> query =
pets.GroupBy(pet => pet.Age, pet => pet.Name);
foreach (IGrouping<int, string> petGroup in query)
{
// Print the key value of the IGrouping.
Console.WriteLine(petGroup.Key);
// Iterate over each value in the
// IGrouping and print the value.
foreach (string name in petGroup)
Console.WriteLine(" {0}", name);
}
}
示例9: FinalTest
public void FinalTest()
{
var buffer1 = new IdHashBuffer(4);
var buffer2 = new IdHashBuffer(4);
buffer1.TryWrite(G1, 1);
buffer1.TryWrite(G2, 2);
buffer1.TryWrite(G3, 3);
buffer1.TryWrite(G4, 3);
buffer1.Seal();
buffer2.TryWrite(G5, 5);
buffer2.TryWrite(G6, 2);
buffer2.TryWrite(G7, 3);
buffer2.TryWrite(G8, 5);
buffer2.Seal();
var collisions = new List<Tuple<ulong, Guid[]>>();
Action<ulong, ArraySegment<Guid>> onCollision = (hash, ids) =>
{
collisions.Add(new Tuple<ulong, Guid[]>(hash, ids.ToArray()));
};
buffer1.FindHashCollisions(new[] { buffer1, buffer2 }, onCollision);
buffer2.FindHashCollisions(new[] { buffer2 }, onCollision);
var collisionDictionary = collisions
.GroupBy(t => t.Item1)
.Select(g => Tuple.Create(g.Key, g.SelectMany(x => x.Item2).Distinct().ToArray()))
.ToDictionary(t => t.Item1, t => t.Item2);
Assert.AreEqual(3, collisionDictionary.Count);
CollectionAssert.AreEquivalent(new[] { G2, G6 }, collisionDictionary[2]);
CollectionAssert.AreEquivalent(new[] { G3, G4, G7 }, collisionDictionary[3]);
CollectionAssert.AreEquivalent(new[] { G5, G8 }, collisionDictionary[5]);
}
示例10: Should_detect_collided_news
public void Should_detect_collided_news()
{
var time = DateTime.Now;
var evtList = new List<EconomicEvent>
{
new EconomicEvent { Currency = "USD", DateTime = time },
new EconomicEvent { Currency = "USD", DateTime = time }
};
var groups = evtList.GroupBy(x => x.DateTime);
Assert.AreEqual(1, groups.Count());
groups.First();
foreach (var grp in groups)
{
Console.WriteLine(grp.Key);
foreach (var item in grp)
{
Console.WriteLine(item.Currency);
}
}
}
示例11: ToDictionaryTestCase
public void ToDictionaryTestCase()
{
var list = new List<Tuple<Int32, String>>
{
new Tuple<Int32, String>( 1, "test1.1" ),
new Tuple<Int32, String>( 1, "test1.2" ),
new Tuple<Int32, String>( 1, "test1.3" ),
new Tuple<Int32, String>( 2, "test2.1" ),
new Tuple<Int32, String>( 2, "test2.2" ),
new Tuple<Int32, String>( 2, "test2.3" ),
new Tuple<Int32, String>( 3, "test3.1" ),
new Tuple<Int32, String>( 3, "test3.2" ),
new Tuple<Int32, String>( 3, "test3.3" )
};
var groups = list.GroupBy( x => x.Item1 );
var actual = groups.ToDictionary();
Assert.AreEqual( 3, actual.Count );
Assert.AreEqual( 3, actual[1].Count );
Assert.AreEqual( 3, actual[2].Count );
Assert.AreEqual( 3, actual[3].Count );
}
示例12: Test
public void Test()
{
List<DataItem> list = new List<DataItem>
{
new DataItem(1, 10.0),
new DataItem(1, 14.0),
new DataItem(2, 20.0),
new DataItem(4, 40.0),
new DataItem(4, 41.0)
};
Dictionary<int, List<double>> expectedDictionary = new Dictionary<int, List<double>>
{
{1, new List<double> {10.0, 14.0}},
{2, new List<double> {20.0}},
{4, new List<double> {40.0, 41.0}}
};
Dictionary<int, List<double>> actualDictionary = list
.GroupBy(dataItem => dataItem.Key, dataItem => dataItem.Value)
.ToDictionary(item => item.Key, item => item.ToList());
Assert.That(actualDictionary.Keys, Is.EquivalentTo(expectedDictionary.Keys));
Assert.That(actualDictionary.Values, Is.EquivalentTo(expectedDictionary.Values));
}
示例13: MessageIdsAreDifferent
public void MessageIdsAreDifferent()
{
var messageIds = new List<string>();
var counter = new SharedCounter(1);
_activator1.Handle<string>(async (bus, ctx, str) =>
{
messageIds.Add(ctx.Headers[Headers.MessageId]);
await bus.Advanced.Routing.Send("bus2", "hej!");
});
_activator2.Handle<string>(async (bus, ctx, str) =>
{
messageIds.Add(ctx.Headers[Headers.MessageId]);
counter.Decrement();
});
_activator1.Bus.SendLocal("heeeej!").Wait();
counter.WaitForResetEvent();
Assert.That(messageIds.GroupBy(i => i).Count(), Is.EqualTo(2));
}
示例14: When_duplicates_found_Should_raise_an_event_for_every_duplicate_set_found
public void When_duplicates_found_Should_raise_an_event_for_every_duplicate_set_found(int testSize)
{
const int NumberOfCollisionsForEach = 2;
var modulo = testSize / NumberOfCollisionsForEach;
var toCreate = Enumerable.Range(0, testSize).Select(i => Tuple.Create(i, Guid.NewGuid())).ToArray();
const int concurrency = 100;
var semaphore = new SemaphoreSlim(concurrency);
foreach (var t in toCreate)
{
semaphore.Wait();
cloudTable.ExecuteAsync(TableOperation.Insert(CreateSagaState(t, modulo)))
.ContinueWith(task =>
{
if (task.Exception != null)
{
Console.WriteLine($"Exception occured {task.Exception}");
}
semaphore.Release();
});
}
for (var i = 0; i < concurrency; i++)
{
semaphore.Wait();
}
var comparer = EqualityComparers.GetValueComparer(EdmType.Int64);
var indexer = new SagaIndexer(cloudTable, "CorrelatingId", o => (ulong)(long)o, comparer);
var results = new List<Tuple<Guid, Guid[]>>();
indexer.SearchForDuplicates((o, guids) => results.Add(Tuple.Create(o, guids.ToArray())));
var dict = results
.GroupBy(t => t.Item1, t => t.Item2, comparer)
.ToDictionary(g => g.Key, g => g.SelectMany(ids => ids).Distinct().ToArray(), comparer);
Assert.AreEqual(modulo, dict.Count);
foreach (var kvp in dict)
{
Assert.AreEqual(2, kvp.Value.Length);
}
}
示例15: KeyedMessagesPreserveOrder
public async void KeyedMessagesPreserveOrder()
{
kafka4net.Tracing.EtwTrace.Marker("KeyedMessagesPreserveOrder");
// create a topic with 3 partitions
var topicName = "part33." + _rnd.Next();
VagrantBrokerUtil.CreateTopic(topicName, 3, 3);
// create listener in a separate connection/broker
var receivedMsgs = new List<ReceivedMessage>();
var consumer = new Consumer(new ConsumerConfiguration(_seed2Addresses, topicName, new StartPositionTopicEnd()));
var consumerSubscription = consumer.OnMessageArrived.Synchronize().Subscribe(msg =>
{
lock (receivedMsgs)
{
receivedMsgs.Add(msg);
}
});
await consumer.IsConnected;
// sender is configured with 50ms batch period
var producer = new Producer(_seed2Addresses, new ProducerConfiguration(topicName, TimeSpan.FromMilliseconds(50)));
await producer.ConnectAsync();
//
// generate messages with 100ms interval in 10 threads
//
var sentMsgs = new List<Message>();
_log.Info("Start sending");
var senders = Enumerable.Range(1, 1).
Select(thread => Observable.
Interval(TimeSpan.FromMilliseconds(10)).
Synchronize(). // protect adding to sentMsgs
Select(i =>
{
var str = "msg " + i + " thread " + thread + " " + Guid.NewGuid();
var bin = Encoding.UTF8.GetBytes(str);
var msg = new Message
{
Key = BitConverter.GetBytes((int)(i + thread) % 10),
Value = bin
};
return Tuple.Create(msg, i, str);
}).
Subscribe(msg =>
{
lock (sentMsgs)
{
producer.Send(msg.Item1);
sentMsgs.Add(msg.Item1);
Assert.AreEqual(msg.Item2, sentMsgs.Count-1);
}
})
).
ToArray();
// wait for around 10K messages (10K/(10*10) = 100sec) and close producer
_log.Info("Waiting for producer to produce enough...");
await Task.Delay(100*1000);
_log.Info("Closing senders intervals");
senders.ForEach(s => s.Dispose());
_log.Info("Closing producer");
await producer.CloseAsync(TimeSpan.FromSeconds(5));
_log.Info("Waiting for additional 10sec");
await Task.Delay(10*1000);
_log.Info("Disposing consumer");
consumerSubscription.Dispose();
_log.Info("Closing consumer");
consumer.Dispose();
_log.Info("Done with networking");
// compare sent and received messages
// TODO: for some reason preformance is not what I'd expect it to be and only 6K is generated.
Assert.GreaterOrEqual(sentMsgs.Count, 4000, "Expected around 10K messages to be sent");
if (sentMsgs.Count != receivedMsgs.Count)
{
var sentStr = sentMsgs.Select(m => Encoding.UTF8.GetString(m.Value)).ToArray();
var receivedStr = receivedMsgs.Select(m => Encoding.UTF8.GetString(m.Value)).ToArray();
sentStr.Except(receivedStr).
ForEach(m => _log.Error("Not received: '{0}'", m));
receivedStr.Except(sentStr).
ForEach(m => _log.Error("Not sent but received: '{0}'", m));
}
Assert.AreEqual(sentMsgs.Count, receivedMsgs.Count, "Sent and received messages count differs");
//
// group messages by key and compare lists in each key to be the same (order should be preserved within key)
//
var keysSent = sentMsgs.GroupBy(m => BitConverter.ToInt32(m.Key, 0), m => Encoding.UTF8.GetString(m.Value), (i, mm) => new { Key = i, Msgs = mm.ToArray() }).ToArray();
var keysReceived = receivedMsgs.GroupBy(m => BitConverter.ToInt32(m.Key, 0), m => Encoding.UTF8.GetString(m.Value), (i, mm) => new { Key = i, Msgs = mm.ToArray() }).ToArray();
Assert.AreEqual(10, keysSent.Count(), "Expected 10 unique keys 0-9");
Assert.AreEqual(keysSent.Count(), keysReceived.Count(), "Keys count does not match");
// compare order within each key
var notInOrder = keysSent
.OrderBy(k => k.Key)
.Zip(keysReceived.OrderBy(k => k.Key), (s, r) => new { s, r, ok = s.Msgs.SequenceEqual(r.Msgs) }).Where(_ => !_.ok).ToArray();
if (notInOrder.Any())
//.........这里部分代码省略.........