本文整理汇总了C#中Microsoft.VisualStudio.TestTools.UnitTesting.List.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# List.ToArray方法的具体用法?C# List.ToArray怎么用?C# List.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.VisualStudio.TestTools.UnitTesting.List
的用法示例。
在下文中一共展示了List.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompileFile
public static CompilerResults CompileFile(string input, string output, params string[] references)
{
CreateOutput(output);
List<string> referencedAssemblies = new List<string>(references.Length + 3);
referencedAssemblies.AddRange(references);
referencedAssemblies.Add("System.dll");
referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
{
if (stream == null)
{
throw new ArgumentException("input");
}
StreamReader reader = new StreamReader(stream);
string source = reader.ReadToEnd();
CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
ThrowIfCompilerError(results);
return results;
}
}
示例2: Eratostenes
private static IEnumerable<long> Eratostenes()
{
const int max = 2000000;
var primes = new List<long>();
var crossedOff = new HashSet<long>();
long candidate = 1;
while (candidate < max)
{
candidate++;
if (crossedOff.Contains(candidate))
{
continue;
}
primes.Add(candidate);
// remove multiples of candidate
for (var i = candidate; i < max + 1; i += candidate)
{
crossedOff.Add(i);
}
}
return primes.ToArray();
}
示例3: TestEncodeDecodeWithCompression
public void TestEncodeDecodeWithCompression()
{
var input =
"He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy.";
var dict = CharacterFrequencyDictionary.CreateDictionary(input);
var encodeTree = new HuffmanTree<char>(dict);
var encode = encodeTree.Encode(input);
var encodeAsByte = CompressUtil.ConvertToByteArray(encode);
var secondDict = CharacterFrequencyDictionary.CreateDictionary(
dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray());
var encodeAsByteArray = new List<byte>();
foreach (var b in encodeAsByte)
encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b));
if (encode.Length < encodeAsByteArray.ToArray().Length)
encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length);
CollectionAssert.AreEqual(dict, secondDict);
CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray());
var decodeTree = new HuffmanTree<char>(secondDict);
var decode = decodeTree.Decode(encodeAsByteArray);
Assert.AreEqual(input, decode);
}
示例4: ArrayLiterals
public void ArrayLiterals()
{
var array = new[] { 42 };
Assert.AreEqual(typeof(int[]), array.GetType(), "You don't have to specify a type if the elements can be inferred");
Assert.AreEqual(new int[] { 42 }, array, "These arrays are literally equal... But you won't see this string in the error message.");
//Are arrays 0-based or 1-based?
Assert.AreEqual(42, array[((int)FILL_ME_IN)], "Well, it's either 0 or 1.. you have a 110010-110010 chance of getting it right.");
//This is important because...
Assert.IsTrue(array.IsFixedSize, "...because Fixed Size arrays are not dynamic");
//Begin RJG
// Moved this Throws() call to a separate FixedSizeArraysCannotGrow() method below
//...it means we can't do this: array[1] = 13;
//Assert.Throws(typeof(FILL_ME_IN), delegate() { array[1] = 13; });
//End RJG
//This is because the array is fixed at length 1. You could write a function
//which created a new array bigger than the last, copied the elements over, and
//returned the new array. Or you could do this:
var dynamicArray = new List<int>();
dynamicArray.Add(42);
CollectionAssert.AreEqual(array, dynamicArray.ToArray(), "Dynamic arrays can grow");
dynamicArray.Add(13);
CollectionAssert.AreEqual((new int[] { 42, (int)FILL_ME_IN }), dynamicArray.ToArray(), "Identify all of the elements in the array");
}
示例5: AddAndGet
public void AddAndGet()
{
var c = new SynchronizedCache();
var lst = new List<Task>();
for (var i = 0; i < 10; i++)
{
var i1 = i;
var t = new Task(() => c.Add(i1, i1.ToString()));
t.Start();
lst.Add(t);
}
Task.WaitAll(lst.ToArray());
Assert.AreEqual(c.Count, 10);
lst.Clear();
for (var i = 0; i < 10; i++)
{
var i1 = i;
var t = new Task(() =>
{
var s = c.Read(i1);
Assert.AreEqual(s, i1.ToString());
c.Update(i1, "42");
});
t.Start();
lst.Add(t);
}
Task.WaitAll(lst.ToArray());
for (var i = 0; i < 10; i++)
{
var s = c.Read(i);
Assert.AreEqual(s, "42");
}
}
示例6: addAllVerticalPointsToListTest
public void addAllVerticalPointsToListTest()
{
List<Point> list = new List<Point>();
List<Point> listExpected = new List<Point>();
int miny = 0;
int maxy = 4;
int x = 1;
listExpected.Add(new Point(x, 0));
listExpected.Add(new Point(x, 1));
listExpected.Add(new Point(x, 2));
listExpected.Add(new Point(x, 3));
listExpected.Add(new Point(x, 4));
ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, true);
Assert.AreEqual(listExpected.Count, list.Count);
Point[] listasarray = list.ToArray();
Point[] expectedlistasarray = listExpected.ToArray();
for (int i = 0; i < listasarray.Length; i++)
{
Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
}
listExpected.Reverse();
list.Clear();
ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, false);
Assert.AreEqual(listExpected.Count, list.Count);
listasarray = list.ToArray();
expectedlistasarray = listExpected.ToArray();
for (int i = 0; i < listasarray.Length; i++)
{
Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
}
}
示例7: PetShopWindowWpfGuiTest
public void PetShopWindowWpfGuiTest()
{
Window window = application.FindWindow(FindBy.UiAutomationId("petShopWindow"));
var petshopWindow = WindowFactory.Create<PetShopMainWindowWpf>(window.Element);
List<String> rules = new List<string>();
rules.Add("Special Environment");
petshopWindow.RegisterAnimal("Foghorn Leghorn", "Large Bird", "Herbivorous", 69.68, rules.ToArray());
petshopWindow.ShowHistory();
petshopWindow.RegisterAnimal("Chickin Lic'in", "Small Bird", "Herbivorous", 666.99, rules.ToArray());
petshopWindow.ShowHistory();
rules.Clear();
rules.Add("Dangerous");
rules.Add("Sell In Pairs");
petshopWindow.RegisterAnimal("Capistrano", "Cat", "Carnivorous", 9.99, rules.ToArray());
petshopWindow.ShowHistory();
}
示例8: AddRangeParamsTest
public void AddRangeParamsTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
JsonObject target;
target = new JsonObject();
target.AddRange(items[0], items[1]);
Assert.AreEqual(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
target = new JsonObject();
target.AddRange(items.ToArray());
Assert.AreEqual(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
ExceptionTestHelper.ExpectException<ArgumentNullException>(delegate { new JsonObject().AddRange((KeyValuePair<string, JsonValue>[])null); });
ExceptionTestHelper.ExpectException<ArgumentNullException>(delegate { new JsonObject().AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)null); });
items[1] = new KeyValuePair<string, JsonValue>(key2, AnyInstance.DefaultJsonValue);
ExceptionTestHelper.ExpectException<ArgumentException>(delegate { new JsonObject().AddRange(items.ToArray()); });
ExceptionTestHelper.ExpectException<ArgumentException>(delegate { new JsonObject().AddRange(items[0], items[1]); });
}
示例9: Merge
// interval: start, end
// sample input: [[1,4],[1,5]] -- 2 interval, (1, 4) (1, 5)
public int[][] Merge(int[][] intervals)
{
List<int[]> result = new List<int[]>();
// order by start first
var tuples = intervals.Select(i => Tuple.Create(i[0], i[1])).OrderBy(t => t.Item1).ToArray();
if (tuples.Length == 0)
{
return result.ToArray();
}
int currentStart = tuples[0].Item1;
int currentEnd = tuples[0].Item2;
for (int i = 1; i < tuples.Length; i++)
{
var currentTuple = tuples[i];
if (currentTuple.Item1 > currentEnd) // no overlap with previous
{
result.Add(new int[] { currentStart, currentEnd });
currentStart = currentTuple.Item1;
currentEnd = currentTuple.Item2;
}
else
{
currentEnd = Math.Max(currentEnd, currentTuple.Item2);
}
}
result.Add(new int[] { currentStart, currentEnd });
return result.ToArray();
}
示例10: ComplexObject_Test
public void ComplexObject_Test()
{
ObjectConverter objectConverter = new ObjectConverter();
objectConverter.RegisterConverter(1, new CreationDictionaryObjectConverter("xtype", new DomainTypeResolver(true)));
Dictionary<string, object> Peter = new Dictionary<string, object>();
Peter["Name"] = "Peter";
List<object> pets = new List<object>();
Dictionary<string, object> xcat = new Dictionary<string, object>();
xcat["xtype"] = typeof(Cat).FullName;
xcat["Name"] = "cat1";
xcat["Age"] = 3;
pets.Add(xcat);
Dictionary<string, object> xdog = new Dictionary<string, object>();
xdog["xtype"] = typeof(Dog).FullName;
xdog["Name"] = "dog1";
xdog["Age"] = 5;
pets.Add(xdog);
Peter["Pets"] = pets.ToArray();
Peter["PetList"] = pets.ToArray();
Person obj = new Person();
objectConverter.MapObject(Peter, obj);
Assert.IsNotNull(obj.Pets);
Assert.AreEqual(2, obj.Pets.Length);
var cat = obj.Pets[0] as Cat;
Assert.IsNotNull(cat);
Assert.AreEqual("cat1", cat.Name);
Assert.AreEqual(3, cat.Age);
var dot = obj.Pets[1] as Dog;
Assert.IsNotNull(dot);
Assert.AreEqual("dog1", dot.Name);
Assert.AreEqual(5, dot.Age);
// check list
Assert.IsNotNull(obj.PetList);
Assert.AreEqual(2, obj.PetList.Count);
cat = obj.PetList[0] as Cat;
Assert.IsNotNull(cat);
Assert.AreEqual("cat1", cat.Name);
Assert.AreEqual(3, cat.Age);
dot = obj.PetList[1] as Dog;
Assert.IsNotNull(dot);
Assert.AreEqual("dog1", dot.Name);
Assert.AreEqual(5, dot.Age);
}
示例11: PetShopWindowWinFormsGuiTest
public void PetShopWindowWinFormsGuiTest()
{
//try
//{
Window window = application.FindWindow(FindBy.UiAutomationId("FormMain"));
var petshopWindow = WindowFactory.Create<PetShopMainWindowWinForm>(window.Element);
////var history = petshopWindow.historyTab.Control;
////history.Select();
//var container = petshopWindow.container.Control;
//var tabControl = petshopWindow.tabctrlAdmin.Control;
////var panel = petshopWindow.registrationTabContainer.Control;
//var text = petshopWindow.name.Control;
//text.Text = "Dave is legendery!";
List<String> rules = new List<string>();
rules.Add("Special Environment");
petshopWindow.RegisterAnimal("Foghorn Leghorn", "Large Bird", "Herbivorous", 69.68, rules.ToArray());
petshopWindow.ShowHistory();
petshopWindow.RegisterAnimal("Chickin Lic'in", "Small Bird", "Herbivorous", 666.99, rules.ToArray());
petshopWindow.ShowHistory();
rules.Clear();
rules.Add("Dangerous");
rules.Add("Sell In Pairs");
petshopWindow.RegisterAnimal("Capistrano", "Cat", "Carnivorous", 9.99, rules.ToArray());
petshopWindow.ShowHistory();
//}
//catch (Exception ex)
//{
// throw;
//}
}
示例12: MergeKLists
public void MergeKLists()
{
var lists = new List<LeetCode.Code.MergeKSortedLists.ListNode>();
var gap = 5;
var eachCount = 10;
var randomDifference = 3;
var random = new Random(Guid.NewGuid().GetHashCode());
var count = gap;
for (var currentStart = 1
; currentStart <= gap
; currentStart++)
{
var firstNode = new LeetCode.Code.MergeKSortedLists.ListNode(currentStart);
lists.Add(firstNode);
for (var index = currentStart + gap
; index <= gap * (eachCount + random.Next(-randomDifference, randomDifference))
; index += gap)
{
firstNode.next = new Code.MergeKSortedLists.ListNode(index);
firstNode = firstNode.next;
count++;
}
}
this.AssertOrdered(mergeKSortedLists.MergeKLists(lists.ToArray()), count);
lists = new List<MergeKSortedLists.ListNode>();
var randomCount = 10000;
for (var index = 0; index < randomCount; index++)
lists.Add(new LeetCode.Code.MergeKSortedLists.ListNode(random.Next(int.MaxValue)));
this.AssertOrdered(mergeKSortedLists.MergeKLists(lists.ToArray()), randomCount);
}
示例13: Insert
public int[][] Insert(int[][] intervals, int[] newInterval)
{
bool inserted = false;
List<int[]> resultList = new List<int[]>();
for (int i = 0; i < intervals.Length; i++)
{
int[] interval = intervals[i];
if (newInterval[0] > interval[1])
{
resultList.Add(interval);
continue;
}
if (newInterval[1] < interval[0])
{
if (!inserted)
{
resultList.Add(newInterval);
inserted = true;
}
resultList.Add(interval);
continue;
}
newInterval[0] = Math.Min(interval[0], newInterval[0]);
newInterval[1] = Math.Max(interval[1], newInterval[1]);
}
if (!inserted)
resultList.Add(newInterval);
return resultList.ToArray();
}
示例14: ValidateUserIdWithRequestCookie
/// <summary>
/// Tests the scenario when the initial request contains a cookie (corresponding to user), in which case, the response should contain a similar cookie with the information
/// replicated into the listener data.
/// </summary>
protected void ValidateUserIdWithRequestCookie(string requestPath, int testListenerTimeoutInMs, int testRequestTimeOutInMs, Cookie[] additionalCookies = null)
{
DateTimeOffset time = DateTimeOffset.UtcNow;
List<Cookie> cookies = new List<Cookie>();
int additionalCookiesLength = 0;
if (null != additionalCookies)
{
cookies.AddRange(additionalCookies);
additionalCookiesLength = additionalCookies.Length;
}
string userCookieStr = "userId|" + time.ToString("O");
var cookie = new Cookie(CookieNames.UserCookie, userCookieStr);
cookies.Add(cookie);
var requestResponseContainer = new RequestResponseContainer(cookies.ToArray(), requestPath, this.Config.ApplicationUri, testListenerTimeoutInMs, testRequestTimeOutInMs);
requestResponseContainer.SendRequest();
var userCookie = requestResponseContainer.CookieCollection.ReceiveUserCookie();
var item = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(
1,
testListenerTimeoutInMs)[0];
Assert.AreEqual("OK", requestResponseContainer.ResponseTask.Result.ReasonPhrase);
Assert.AreEqual(2 + additionalCookiesLength, requestResponseContainer.CookieCollection.Count);
Assert.AreEqual("userId", item.UserContext.Id);
Assert.AreEqual(time, item.UserContext.AcquisitionDate.Value);
Assert.AreEqual(userCookieStr, userCookie);
Assert.AreEqual(userCookie, item.UserContext.Id + "|" + item.UserContext.AcquisitionDate.Value.ToString("O"));
}
示例15: CrossProcessBarrierTest
public void CrossProcessBarrierTest()
{
IEnumerable<string> allNames = new List<string>
{
"deployment(400).GenericWorkerRole.Cloud.WebRole.0_Web",
"deployment(400).GenericWorkerRole.Cloud.WebRole.1_Web",
"deployment(400).GenericWorkerRole.Cloud.WebRole.2_Web",
"deployment(400).GenericWorkerRole.Cloud.WebRole.3_Web",
"deployment(400).GenericWorkerRole.Cloud.WebRole.4_Web"
};
Func<string, string> escapeMutexName = instanceId => instanceId.Replace("(", ".").Replace(")", ".").Replace(".", "");
allNames = allNames.Select(escapeMutexName);
var tasks = new List<Task>();
foreach (var currentName in allNames)
{
var peerNames = new List<string>(allNames);
peerNames.Remove(currentName);
var c = CrossProcessBarrier.GetInstance(currentName, peerNames, TimeSpan.Zero);
tasks.Add(Task.Factory.StartNew(c.Wait));
Trace.TraceInformation("Launched task {0}", currentName);
}
Trace.TraceInformation("Waiting for all tasks to reach the barrier");
Task.WaitAll(tasks.ToArray());
Trace.TraceInformation("All tasks reached the barrier");
}