本文整理汇总了C#中Microsoft.VisualStudio.TestTools.UnitTesting.List.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# List.GroupBy方法的具体用法?C# List.GroupBy怎么用?C# List.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.VisualStudio.TestTools.UnitTesting.List
的用法示例。
在下文中一共展示了List.GroupBy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestMethod1
public void TestMethod1()
{
var dateTimeFuncs = new Func<Double, TimeSpan>[] {
TimeSpan.FromSeconds,
TimeSpan.FromMinutes,
TimeSpan.FromHours,
TimeSpan.FromDays,
x => TimeSpan.FromDays(30 * x),
x => TimeSpan.FromDays(365 * x),
};
var allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
var supportedCultures = new List<CultureInfo>();
foreach (var culture in allCultures) {
try {
var dateTimeFormatStrings = DateTimeExtensions.GetFormatString(culture);
supportedCultures.Add(culture);
}
catch (NotSupportedException) {}
}
var distinctSupportedLanguageCultures = supportedCultures.GroupBy(x => x.ThreeLetterISOLanguageName).Select(x => x.First()).ToList();
foreach (var culture in distinctSupportedLanguageCultures) {
foreach (var dateTimeFunc in dateTimeFuncs) {
for (var i = 0; i != 3; i++) {
var dateTime = DateTime.Now.Subtract(dateTimeFunc(i));
var timeAgo = dateTime.TimeAgo(culture);
Debug.WriteLine(timeAgo);
}
}
}
}
示例2: GetReport_Returns_5_Elements_For_5_Input
public void GetReport_Returns_5_Elements_For_5_Input()
{
string skill1 = "C#";
string skill2 = "JavaScript";
string skill3 = "C";
DateTime date1 = new DateTime(year: 2016, month: 2, day: 8);
IQueryable<CandidateInformation> _CandidateInfoColl = new List<CandidateInformation>()
{
new CandidateInformation() { SkillSet = skill1, SavedOn = date1 },
new CandidateInformation() { SkillSet = skill1, SavedOn = date1 },
new CandidateInformation() { SkillSet = skill2, SavedOn = date1 },
new CandidateInformation() { SkillSet = skill3, SavedOn = date1 },
new CandidateInformation() { SkillSet = skill3, SavedOn = date1 },
}.AsQueryable();
DateTime reportDate = date1;
IRepository<CandidateInformation> mockCandidateInfoRepository = MockRepository.GenerateMock<IRepository<CandidateInformation>>();
mockCandidateInfoRepository.Stub(x => x.Find(Arg<Expression<Func<CandidateInformation, bool>>>.Is.Anything)).Return(_CandidateInfoColl);
IReportGenerator reportGenerator = new ReportGenerator(reportDate, mockCandidateInfoRepository);
IEnumerable<string> actualOutput = reportGenerator.GetReport();
IEnumerable<string> expectedOutput = _CandidateInfoColl.GroupBy(x => x.SkillSet)
.OrderBy(x => x.Key)
.Select(x => string.Format("{0},{1}", x.Key, x.Count()));
mockCandidateInfoRepository.AssertWasCalled(x => x.Find(Arg<Expression<Func<CandidateInformation, bool>>>.Is.Anything));
Assert.AreEqual(expectedOutput.Count() + 1, actualOutput.Count()); //Added 1 to compensate for the header row.
foreach (string expectedString in expectedOutput)
{
Assert.IsTrue(actualOutput.Contains(expectedString));
}
}
示例3: EnsureDeckHasRightNumberOfSuites
public void EnsureDeckHasRightNumberOfSuites()
{
var testDeck = new PrivateObject(typeof(Deck));
var cardsInTestDeck = new List<Card>((Stack<Card>)testDeck.GetFieldOrProperty("_cards"));
var result = cardsInTestDeck.GroupBy(card => card.Suit);
Assert.IsFalse(result.Count() < 4, "Suits Error", "The deck contains less than four suits.");
Assert.IsFalse(result.Count() > 4, "Suits Error", "The deck contains more than four suits.");
}
示例4: EnsureDeckHasRightNumberOfValues
public void EnsureDeckHasRightNumberOfValues()
{
var testDeck = new PrivateObject(typeof(Deck));
var cardsInTestDeck = new List<Card>((Stack<Card>)testDeck.GetFieldOrProperty("_cards"));
var result = cardsInTestDeck.GroupBy(card => card.Value);
Assert.IsFalse(result.Count() < 13, "Value Error", "The deck contains less than thirteen values.");
Assert.IsFalse(result.Count() > 13, "Value Error", "The deck contains more than thirteen values.");
}
示例5: IntEqualityComparerTest
public void IntEqualityComparerTest()
{
var source = new List<int> { 1, 5, 5, 2,7,12,15,18,20,24,25,10,5,1,8,11,30 };
var comparer = new IntEqualityComparer(5);
source.Sort();
var res = source.GroupBy(g => g, comparer);
Assert.AreEqual(5, res.Count());
}
示例6: GameHandlerReturnsRandomColors
public void GameHandlerReturnsRandomColors()
{
GameHandler gameHandler = new GameHandler();
List<List<GameColors>> colors = new List<List<GameColors>>();
//1000 is a large enough number to reduce the the chance of getting the same color in the first position
//beyond probable infinity (1/8)^1000
for (int i = 0; i < 1000; i++)
{
colors.Add(gameHandler.GetInitialColors());
}
Assert.IsTrue(colors.GroupBy(f => f.First()).Count() > 1, "Colors returned by GameHandler does not appear to be random.");
}
示例7: DLINQPerformsDistributedGroupBy
public void DLINQPerformsDistributedGroupBy()
{
bool isFailed = false;
BluepathListener listener1;
BluepathListener listener2;
ConnectionManager connectionManager;
Log.TraceMessage(Log.Activity.Custom,string.Format("GroupBy test lift off!"));
PrepareDLINQEnviroment(out listener1, out listener2, out connectionManager);
try
{
var inputCollection = new List<string>();
for (int i = 0; i < 100; i++)
{
inputCollection.Add(string.Format("{0}{1}", (i % 2 == 0 ? "a" : "b"), i));
}
var locallyGrouped = inputCollection.GroupBy(s => s[0]);
var localDict = locallyGrouped.ToDictionary(g => g.Key, g => g);
var storage = new RedisStorage(Host);
var groupedCollection = inputCollection.AsDistributed(storage, connectionManager)
.GroupBy(s => s[0]);
Log.TraceMessage(Log.Activity.Custom,"GroupBy Begin actual processing");
var processedCollection = groupedCollection.ToDictionary(g => g.Key, g => g);
Log.TraceMessage(Log.Activity.Custom,"GroupBy processing finished, begin asserts");
processedCollection.Keys.Count.ShouldBe(2);
processedCollection['a'].Count().ShouldBe(localDict['a'].Count());
processedCollection['b'].Count().ShouldBe(localDict['b'].Count());
Log.TraceMessage(Log.Activity.Custom,"GroupBy test passed");
}
catch (Exception ex)
{
Log.ExceptionMessage(ex, Log.Activity.Info);
isFailed = true;
}
finally
{
listener1.Stop();
listener2.Stop();
Log.TraceMessage(Log.Activity.Custom, string.Format("GroupBy test finished, isFailed: {0}", isFailed));
if(isFailed)
{
Assert.Fail();
}
}
}
示例8: TestFindDuplicates_DetectDuplicates
public void TestFindDuplicates_DetectDuplicates()
{
Random random = new Random();
// build a list of random values
var list = new List<int>(100);
Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist());
// duplicates must appear next to each other
list.ToSublist().Sort().InPlace();
var result = list.ToSublist().FindDuplicates();
if (!result.Exists)
{
Assert.AreEqual(list.Count, list.GroupBy(i => i).Count(), "Duplicates were not detected.");
}
else
{
var actual = list.ToSublist(result.Index, 2);
int[] expected = new int[2] { list[result.Index], list[result.Index] };
Assert.IsTrue(expected.ToSublist().IsEqualTo(actual), "No duplicates were not found.");
}
}
示例9: ObservableThreadsWithThrottleOnCompute
public void ObservableThreadsWithThrottleOnCompute()
{
Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId);
BehaviorSubject<int> s1 = new BehaviorSubject<int>(2);
BehaviorSubject<int> s2 = new BehaviorSubject<int>(3);
BehaviorSubject<int> sum = new BehaviorSubject<int>(5);
List<int> computeThreads = new List<int>();
List<int> receiveThreads = new List<int>();
IScheduler computeScheduler = new EventLoopScheduler();
IObservable<int> sumObservable = s1.Throttle(TimeSpan.FromMilliseconds(100), computeScheduler).ObserveOn(computeScheduler).CombineLatest(s2.Throttle(TimeSpan.FromMilliseconds(100), computeScheduler).ObserveOn(computeScheduler), (first, second) =>
{
Console.WriteLine("Computing value " + first + " + " + second + " = " + (first + second) + " on Thread " + Thread.CurrentThread.ManagedThreadId + ".");
computeThreads.Add(Thread.CurrentThread.ManagedThreadId);
return first + second;
});
sumObservable.Subscribe(sum.OnNext);
sum.ObserveOn(new EventLoopScheduler()).Subscribe(v =>
{
Console.WriteLine("Received value " + v + " on Thread " + Thread.CurrentThread.ManagedThreadId + ".");
receiveThreads.Add(Thread.CurrentThread.ManagedThreadId);
});
Thread.Sleep(150);
s2.OnNext(1);
Thread.Sleep(50);
s1.OnNext(4);
Thread.Sleep(150);
s2.OnNext(4);
Thread.Sleep(250);
s1.OnNext(1);
Thread.Sleep(150);
foreach (KeyValuePair<int, int> p in
computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count())))
{
Console.WriteLine(p.Value + " computes on Thread " + p.Key);
}
foreach (KeyValuePair<int, int> p in
receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count())))
{
Console.WriteLine(p.Value + " receives on Thread " + p.Key);
}
}
示例10: TestJoinLists
public void TestJoinLists()
{
// Create a new list of apps
var apps = new List<EmailApplication>() {
new EmailApplication() {Id = 1, CustomerId = 1, IPAccessRestrictions = "123.43.56.2"},
new EmailApplication() {Id = 2, CustomerId = 1, IPAccessRestrictions = "123.43.56.36"},
new EmailApplication() {Id = 3, CustomerId = 1},
new EmailApplication() {Id = 4, CustomerId = 2},
new EmailApplication() {Id = 5, CustomerId = 3, IPAccessRestrictions = "123.43.45.1"}
};
var customers = new List<Customer>();
foreach (var customer in m_repository.GetSortedCustomers())
{
// customer.Applications = apps.Where(a => a.CustomerId == customer.Id).ToList();
customers.Add(customer);
}
// Join customers to applications (with filter to those with IP restrictions)
var joinQuery = customers.Join(apps,
c => c.Id,
a => a.CustomerId,
(c, a) => new
{
Name = c.LastName + ", " + c.FirstName,
IpRestrictions = a.IPAccessRestrictions
}).Where(w => !String.IsNullOrEmpty(w.IpRestrictions));
foreach (var item in joinQuery)
{
Debug.WriteLine(item.Name.ToString() + " : " + item.IpRestrictions);
}
// Try to get customers with IP access restrictions
var manyQuery = customers
.Select(c => c.Applications
.Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions)));
foreach (var item in manyQuery)
{
Debug.WriteLine(item.ToString());
}
// The above query is an enumerable of an enumerable, which ain't great
// Using SelectMany will flatten a parent/child relationship and allow projection on either
var customersWithIpRestrictions = customers
.SelectMany(c => c.Applications
.Where(a => !String.IsNullOrEmpty(a.IPAccessRestrictions)),
// project to customer
(c, a) => c)
.Distinct();
foreach (var item in customersWithIpRestrictions)
{
Debug.WriteLine(item.LastName + ", " + item.FirstName);
}
Debug.WriteLine(customers.Sum(c => 1));
var groupBy = apps.GroupBy(a => a.CustomerId,
a => a.Id,
(key, id) => new
{
ClientId = key,
NumApps = id.Sum(a => 1),
MeanApps = id.Sum() / id.Sum(a => 1),
Avg = id.Average()
});
foreach (var item in groupBy)
{
Debug.WriteLine(item.ClientId + " has this many apps: " + item.NumApps + " with mean: " + item.Avg);
}
var modeJoin = apps.Join(customers,
a => a.CustomerId,
c => c.Id,
(a, c) => new
{
ClientName = c.LastName + ", " + c.FirstName,
ApplicationId = a.Id
});
var modeQuery = modeJoin.GroupBy(e => e.ClientName)
.OrderByDescending(group => group.Count())
.Select(group => group.Key);
Debug.WriteLine("ClientId with most apps: " + modeQuery.FirstOrDefault());
Assert.IsNotNull(joinQuery);
}
示例11: ScaleRetrievalTest
public void ScaleRetrievalTest()
{
var manager = new QueueMessageManagerSql();
manager.Db.ExecuteNonQuery("delete from queuemessageitems");
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 30000; i++)
{
string imageId = "10";
// Create a message object
// item contains many properties for pushing
// values back and forth as well as a few message fields
var item = manager.CreateItem();
item.QueueName = "Queue1";
item.TextInput = DataUtils.GenerateUniqueId(15);
// Set the message status and timestamps as submitted
manager.SubmitRequest(item,autoSave: true);
}
Console.WriteLine("Insert time: " + sw.ElapsedMilliseconds);
IdList = new List<string>();
IdErrors = new List<string>();
for (int i = 0; i < 20; i++)
{
var thread = new Thread(ProcessGetNextItem);
thread.Start();
}
for (int i = 0; i < 10000; i++)
{
if (CancelProcessing)
break;
string imageId = "10";
// Create a message object
// item contains many properties for pushing
// values back and forth as well as a few message fields
var item = manager.CreateItem();
item.QueueName = "Queue1";
item.TextInput = DataUtils.GenerateUniqueId(15);
// Set the message status and timestamps as submitted
manager.SubmitRequest(item, autoSave: true);
Thread.Sleep(2);
}
Console.WriteLine("Waiting for 5 seconds");
Thread.Sleep(5000);
CancelProcessing = true;
Thread.Sleep(100);
Console.WriteLine("Done");
Console.WriteLine("Items processed: " + IdList.Count);
var grouped = IdList.GroupBy(s => s);
Console.WriteLine("Unique Count: " + grouped.Count());
foreach (var error in IdErrors)
Console.WriteLine(" " + error);
}
示例12: ScaleControllerRetrievalTest
public void ScaleControllerRetrievalTest()
{
var manager = new QueueMessageManagerMongoDb(CONNECTION_STRING);
manager.Collection.RemoveAll();
CancelProcessing = false;
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 30000; i++)
{
string imageId = "10";
// Create a message object
// item contains many properties for pushing
// values back and forth as well as a few message fields
var item = manager.CreateItem();
item.QueueName = "Queue1";
item.TextInput = DataUtils.GenerateUniqueId(15);
// Set the message status and timestamps as submitted
manager.SubmitRequest(item, autoSave: true);
}
Console.WriteLine("Done adding: " + sw.ElapsedMilliseconds + "ms");
Console.WriteLine("Items inserted.");
IdList = new List<string>();
IdErrors = new List<string>();
for (int i = 0; i < 10; i++)
{
var thread = new Thread(ProcessGetNextItem);
thread.Start();
}
//Task.Run(() =>
//{
// for (int i = 0; i < 100; i++)
// {
// manager = new QueueMessageManagerSql();
// string imageId = "10";
// // Create a message object
// // item contains many properties for pushing
// // values back and forth as well as a few message fields
// var item = manager.CreateItem();
// item.QueueName = "Queue1";
// item.TextInput = DataUtils.GenerateUniqueId(15);
// // Set the message status and timestamps as submitted
// manager.SubmitRequest(item, autoSave: true);
// }
// Thread.Sleep(60);
//});
for (int i = 0; i < 500; i++)
{
if (CancelProcessing)
break;
string imageId = "10";
// Create a message object
// item contains many properties for pushing
// values back and forth as well as a few message fields
var item = manager.CreateItem();
item.QueueName = "Queue1";
item.TextInput = DataUtils.GenerateUniqueId(15);
// Set the message status and timestamps as submitted
manager.SubmitRequest(item, autoSave: true);
Thread.Yield();
}
Console.WriteLine("Waiting for 5 seconds");
Thread.Sleep(5000);
CancelProcessing = true;
Thread.Sleep(150);
Console.WriteLine("Done");
Console.WriteLine("Items processed: " + IdList.Count);
IdList.Add("12345");
IdList.Add("321321");
IdList.Add("12345");
var grouped = IdList.GroupBy(s => s);
Console.WriteLine("Unique Count: " + grouped.Count());
foreach (var error in IdErrors)
Console.WriteLine(" " + error);
}
开发者ID:RickStrahl,项目名称:Westwind.QueueMessageManager,代码行数:100,代码来源:BasicQueueMessageManagerMongoDbTests.cs
示例13: GroupBy_abnormal
public void GroupBy_abnormal()
{
// arrange
List<Javascript> list = new List<Javascript>() {
new Javascript("Angular", 1),
new Javascript("React", 1),
new Javascript("Backbone", 5)
};
Func<Javascript, Javascript> func = null;
// act and assert
try
{
list.GroupBy(func);
Assert.Fail();
}
catch (Exception e)
{
Assert.IsTrue(e is ArgumentNullException);
}
}
示例14: TestLiveListGroupBy2
public void TestLiveListGroupBy2()
{
var data =
new List<A>()
.ToLiveList();
data.TraceAll("data").ToDebug();
using (Publish.Transaction(true))
{
Enumerable.Range(0, 7)
.ForEach(i =>
{
var aa = new A();
aa.I.Init(i % 5, 0);
data.PublishInner.Add(aa);
});
}
var a = data
.GroupBy(i => i.I)
.ToIndependent();
a.TraceAll("a").ToDebug();
}
示例15: AsyncObservableThreadsWithBetterThrottleOnComputeAndIsCalculating
public void AsyncObservableThreadsWithBetterThrottleOnComputeAndIsCalculating()
{
Console.WriteLine("Starting Thread " + Thread.CurrentThread.ManagedThreadId);
BehaviorSubject<int> s1 = new BehaviorSubject<int>(2);
BehaviorSubject<int> s2 = new BehaviorSubject<int>(3);
BehaviorSubject<int> sum = new BehaviorSubject<int>(5);
List<int> computeThreads = new List<int>();
List<int> receiveThreads = new List<int>();
IScheduler throttleScheduler = new EventLoopScheduler();
Func<IScheduler> getComputeScheduler = () => new EventLoopScheduler();
IScheduler receiveScheduler = new EventLoopScheduler();
IObservable<Tuple<int, int>> sumObservable = s1.CombineLatest(s2, Tuple.Create).Throttle(TimeSpan.FromMilliseconds(100), throttleScheduler);
IDisposable sumObservableSubscription = null;
using (sumObservable.Subscribe(v =>
{
if (sumObservableSubscription != null)
{
Console.WriteLine("Canceling previous.");
sumObservableSubscription.Dispose();
}
sumObservableSubscription = Observable.Create<int>((o, token) => Task.Factory.StartNew(() =>
{
Thread.Sleep(200);
if (!token.IsCancellationRequested)
{
Console.WriteLine("Computing value " + v.Item1 + " + " + v.Item2 + " = " + (v.Item1 + v.Item2) + " on Thread " + Thread.CurrentThread.ManagedThreadId + ".");
computeThreads.Add(Thread.CurrentThread.ManagedThreadId);
o.OnNext(v.Item1 + v.Item2);
}
o.OnCompleted();
return Disposable.Empty;
})).ObserveOn(receiveScheduler).Subscribe(v2 =>
{
Console.WriteLine("Received value " + v2 + " on Thread " + Thread.CurrentThread.ManagedThreadId + ".");
receiveThreads.Add(Thread.CurrentThread.ManagedThreadId);
});
}))
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Thread.Sleep(150);
s2.OnNext(1);
Thread.Sleep(50);
s1.OnNext(4);
Thread.Sleep(250);
s2.OnNext(4);
Thread.Sleep(150);
s1.OnNext(1);
Thread.Sleep(350);
stopwatch.Stop();
Console.WriteLine("Total Time: " + stopwatch.ElapsedMilliseconds + " ms");
foreach (KeyValuePair<int, int> p in
computeThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count())))
{
Console.WriteLine(p.Value + " computes on Thread " + p.Key);
}
foreach (KeyValuePair<int, int> p in
receiveThreads.GroupBy(v => v).Select(g => new KeyValuePair<int, int>(g.Key, g.Count())))
{
Console.WriteLine(p.Value + " receives on Thread " + p.Key);
}
}
}