本文整理汇总了C#中SortedList.GetByIndex方法的典型用法代码示例。如果您正苦于以下问题:C# SortedList.GetByIndex方法的具体用法?C# SortedList.GetByIndex怎么用?C# SortedList.GetByIndex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedList
的用法示例。
在下文中一共展示了SortedList.GetByIndex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ShortestPath
public Stack ShortestPath(GameObject start, GameObject end)
{
InitializeNodesForShortestPath();
start.GetComponent<NavpointScript>().SetDist(0f);
SortedList nodes = new SortedList();
nodes.Add (0f, start);
while(nodes.Count > 0){
if(end.Equals ((GameObject)nodes.GetByIndex (0))){
break;
}
NavpointScript u = ((GameObject)nodes.GetByIndex (0)).GetComponent<NavpointScript>();
nodes.RemoveAt (0);
u.SetVisited();
GameObject[] adj = u.GetAdjacentNodes();
for(int i = 0; i < adj.Length; i++){
NavpointScript v = adj[i].GetComponent<NavpointScript>();
float alt = u.GetDistByIndex (i) + u.GetDist ();
if(alt < v.GetDist () && !v.Visited ()){
v.SetDist(alt);
v.SetPrev(u.gameObject);
if(nodes.ContainsValue (v))
nodes.RemoveAt (nodes.IndexOfValue (v));
nodes.Add (alt, v.gameObject);
}
}
}
Stack s = new Stack();
GameObject node = end;
while(node != null){
s.Push(node);
node = node.GetComponent<NavpointScript>().GetPrev();
}
return s;
}
示例2: Start
// Use this for initialization
void Start()
{
navManager = GameObject.FindGameObjectWithTag ("NavManager").GetComponent<NavmanagerScript>();
mask = navManager.navMask;
SortedList adjacentNav = new SortedList();
GameObject[] navs = navManager.GetNavGroupManager().GetComponent<NavgroupScript>().GetPointsInSharedGroups(gameObject);
for(int i = 0; i < navs.Length; i++){
if(!navs[i].Equals (gameObject) && !Physics2D.Linecast(transform.position, navs[i].transform.position, mask)){
adjacentNav.Add(Vector3.Distance (transform.position, navs[i].transform.position), navs[i]);
}
}
adjNodes = new GameObject[adjacentNav.Count];
dists = new float[adjacentNav.Count];
for(int i = 0; i < adjacentNav.Count; i++){
adjNodes[i] = (GameObject)(adjacentNav.GetByIndex (i));
dists[i] = Vector3.Distance (transform.position, adjNodes[i].transform.position);
}
}
示例3: GetTransforms
/// <summary>
/// Returns children transforms, sorted by name.
/// </summary>
Transform[] GetTransforms()
{
if (SplineRoot != null)
{
SortedList mySL = new SortedList();
foreach (Transform child in SplineRoot.transform)
mySL.Add(child.name, child);
mySL.Remove(SplineRoot.transform.name);
Transform[] ret = new Transform[mySL.Count];
for (int i=0;i<mySL.Count;i++)
ret[i] = (Transform)mySL.GetByIndex(i);
return ret;
}
return null;
}
示例4: DoIListTests
private void DoIListTests(SortedList good, IList bad, Hashtable hsh1, DicType dic)
{
if (bad.IsReadOnly != good.IsReadOnly)
hsh1["IsReadOnly"] = "";
if (bad.IsFixedSize != good.IsFixedSize)
hsh1["IsFixedSize"] = "";
try
{
if (dic == DicType.Key)
{
DoICollectionTests(good, bad, hsh1, DicType.Key);
for (int i = 0; i < good.Count; i++)
{
if (!bad.Contains(good.GetKey(i)))
hsh1["Contains"] = i;
if (bad[i] != good.GetKey(i))
hsh1["Item"] = "get";
if (bad.IndexOf(good.GetKey(i)) != i)
hsh1["IndexOf"] = i;
}
//we change the original and see if it is reflected in the IList
good.Add("ThisHasToBeThere", null);
if (!bad.Contains("ThisHasToBeThere"))
hsh1["Contains"] = "Modified";
if (bad.Count != bad.Count)
hsh1["Count"] = "Modified";
}
else if (dic == DicType.Value)
{
DoICollectionTests(good, bad, hsh1, DicType.Value);
for (int i = 0; i < good.Count; i++)
{
if (!bad.Contains(good.GetByIndex(i)))
hsh1["Contains"] = i;
if (bad[i] != good.GetByIndex(i))
hsh1["Item"] = "get";
if (bad.IndexOf(good.GetByIndex(i)) != i)
hsh1["IndexOf"] = i;
}
//we change the original and see if it is reflected in the IList
good.Add("ThisHasToBeThere", "ValueWasJustAdded");
if (!bad.Contains(good["ThisHasToBeThere"]))
hsh1["Contains"] = "Modified";
if (bad.Count != bad.Count)
hsh1["Count"] = "Modified";
}
try
{
bad.Add("AnyValue");
hsh1["Add"] = "No_Exception thrown";
}
catch (NotSupportedException)
{
}
catch (Exception ex)
{
hsh1["Add"] = ex.GetType().Name;
}
if (bad.Count != bad.Count)
hsh1["Count"] = "ReadWrite";
try
{
bad.Clear();
hsh1["Clear"] = "No_Exception thrown";
}
catch (NotSupportedException)
{
}
catch (Exception ex)
{
hsh1["Clear"] = ex.GetType().Name;
}
try
{
bad.Insert(0, "AnyValue");
hsh1["Insert"] = "No_Exception thrown";
}
catch (NotSupportedException)
{
}
catch (Exception ex)
{
hsh1["Insert"] = ex.GetType().Name;
}
try
{
bad.Remove("AnyValue");
hsh1["Remove"] = "No_Exception thrown";
}
catch (NotSupportedException)
{
}
catch (Exception ex)
//.........这里部分代码省略.........
示例5: Main
static void Main()
{
/* Write a program that finds the most frequent number in an array. Example:
* {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} 4 (5 times) */
Console.Write("Enter array lenght (or 0 for array autogeneration): ");
int n = int.Parse(Console.ReadLine());
int[] arr;
if (n == 0)
{
// random generated array
Random rnd = new Random();
n = rnd.Next(20, 30);
arr = new int[n];
Console.WriteLine("Generated N is: {0}", n);
Console.WriteLine("Generated array is:");
for (int i = 0; i < n; i++)
{
arr[i] = rnd.Next(10);
Console.Write("{0,2}", arr[i]);
}
Console.WriteLine();
}
else
{
// user defined and fileld array
arr = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Element {0}: ", i + 1);
arr[i] = int.Parse(Console.ReadLine());
}
}
// input is done
SortedList count = new SortedList(); // I use SortedList to automate some work. "Index" field is value of element, "value" element is count of this elements
for (int i = 0; i < arr.Length; i++) // let's walk in array - form start to end
{
int index = count.IndexOfKey(arr[i]); // is this element already in sorted list?
if (index < 0)
count.Add(arr[i], 1); // no, this element is not in the list. Add them, and place "1" at count position
else
count[arr[i]] = (int)count[arr[i]]+1 ; // yes, element is in the list. Add 1 to count position.
}
//count of all elements is done
int maxPos = 0; // now we must find which element have biggest count (in "value" fielt in sorted array)
int maxValue = (int)count.GetByIndex(0); // get first element for starting
for (int i = 1; i < count.Count; i++)
{
if (maxValue < (int)count.GetByIndex(i))
{
maxPos = i;
maxValue = (int)count.GetByIndex(i);
}
}
//finding the most frequent element is done
Console.WriteLine("Value {0} is most frequent - {1} times",count.GetKey(maxPos),maxValue) ;
for (int i = 0; i < n; i++)
{
if (arr[i] == (int)count.GetKey(maxPos))
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("{0,2}", arr[i]);
Console.ForegroundColor = ConsoleColor.Gray;
}
Console.WriteLine();
}
示例6: RecycleServicePoints
// Internal Methods
internal static void RecycleServicePoints ()
{
ArrayList toRemove = new ArrayList ();
lock (servicePoints) {
IDictionaryEnumerator e = servicePoints.GetEnumerator ();
while (e.MoveNext ()) {
ServicePoint sp = (ServicePoint) e.Value;
if (sp.AvailableForRecycling) {
toRemove.Add (e.Key);
}
}
for (int i = 0; i < toRemove.Count; i++)
servicePoints.Remove (toRemove [i]);
if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
return;
// get rid of the ones with the longest idle time
SortedList list = new SortedList (servicePoints.Count);
e = servicePoints.GetEnumerator ();
while (e.MoveNext ()) {
ServicePoint sp = (ServicePoint) e.Value;
if (sp.CurrentConnections == 0) {
while (list.ContainsKey (sp.IdleSince))
sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
list.Add (sp.IdleSince, sp.Address);
}
}
for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
servicePoints.Remove (list.GetByIndex (i));
}
}
示例7: TestGetEnumeratorBasic
public void TestGetEnumeratorBasic()
{
StringBuilder sblMsg = new StringBuilder(99);
//
SortedList sl2 = null;
IDictionaryEnumerator dicen = null;
StringBuilder sbl3 = new StringBuilder(99);
StringBuilder sbl4 = new StringBuilder(99);
StringBuilder sblWork1 = new StringBuilder(99);
int i3 = 0;
int i2 = 0;
int i = 0;
int j = 0;
//
// Constructor: Create SortedList using this as IComparer and default settings.
//
sl2 = new SortedList(this);
// Verify that the SortedList is not null.
Assert.NotNull(sl2);
// Verify that the SortedList is empty.
Assert.Equal(0, sl2.Count);
// Testcase: Set - null key, ArgExc expected
Assert.Throws<ArgumentNullException>(() =>
{
sl2[null] = 0;
});
Assert.Equal(0, sl2.Count);
// Testcase: Set - null val
sl2[(object)100] = (object)null;
Assert.Equal(1, sl2.Count);
// Testcase: vanila Set
sl2[(object)100] = 1;
Assert.Equal(1, sl2.Count);
sl2.Clear();
Assert.Equal(0, sl2.Count);
// Testcase: add key-val pairs
for (i = 0; i < 100; i++)
{
sl2.Add(i + 100, i);
}
Assert.Equal(100, sl2.Count);
for (i = 0; i < 100; i++)
{
j = i + 100;
Assert.True(sl2.ContainsKey((int)j));
Assert.True(sl2.ContainsValue(i));
object o2 = sl2[(object)(j)]; //need to cast: Get (object key)
Assert.NotNull(o2);
i2 = (int)o2;
i3 = (int)sl2.GetByIndex(i); //Get (index i)
Assert.False((i3 != i) || (i2 != i));
// testcase: GetEnumerator
dicen = (IDictionaryEnumerator)sl2.GetEnumerator();
// Boundary for Current
Assert.Throws<InvalidOperationException>(() =>
{
object throwaway = dicen.Current;
}
);
j = 0;
// go over the enumarator
while (dicen.MoveNext())
{
// Current to see the order
i3 = (int)dicen.Value;
Assert.True(j.Equals(i3));
// Current again to see the same order
i3 = (int)dicen.Value;
Assert.Equal(i3, j);
j++;
}
// Boundary for Current
Assert.Throws<InvalidOperationException>(() =>
{
object throwaway = dicen.Current;
//.........这里部分代码省略.........
示例8: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
string downloadDir = ConfigurationManager.AppSettings["downloadDir"];
string html = GetDownloadDirectoryOutput(downloadDir);
//string html = "<head><title>build.mutantdesign.co.uk - /builds/</title></head><body><H1>build.mutantdesign.co.uk - /builds/</H1><hr><pre><A HREF=\" / \">[To Parent Directory]</A><br><br> Monday, November 21, 2005 8:33 PM 2251973 <A HREF=\"/builds/MbUnit-2.3.0.exe\">MbUnit-2.3.0.exe</A><br> Wednesday, November 23, 2005 9:36 AM 2251958 <A HREF=\"/builds/MbUnit-2.3.1.exe\">MbUnit-2.3.1.exe</A><br> Monday, December 12, 2005 9:43 PM 2231225 <A HREF=\"/builds/MbUnit-2.3.11.exe\">MbUnit-2.3.11.exe</A><br> Wednesday, December 14, 2005 10:51 AM 2239306 <A HREF=\"/builds/MbUnit-2.3.13.exe\">MbUnit-2.3.13.exe</A><br> Sunday, December 18, 2005 6:04 PM 2238969 <A HREF=\"/builds/MbUnit-2.3.15.exe\">MbUnit-2.3.15.exe</A><br> Sunday, December 18, 2005 6:10 PM 2238976 <A HREF=\"/builds/MbUnit-2.3.16.exe\">MbUnit-2.3.16.exe</A><br> Sunday, December 18, 2005 6:13 PM 2238980 <A HREF=\"/builds/MbUnit-2.3.17.exe\">MbUnit-2.3.17.exe</A><br> Wednesday, January 04, 2006 1:49 AM 1294082 <A HREF=\"/builds/MbUnit-2.3.19.exe\">MbUnit-2.3.19.exe</A><br> Wednesday, November 23, 2005 9:53 AM 2251951 <A HREF=\"/builds/MbUnit-2.3.2.exe\">MbUnit-2.3.2.exe</A><br> Thursday, January 19, 2006 2:59 PM 1294202 <A HREF=\"/builds/MbUnit-2.3.22.exe\">MbUnit-2.3.22.exe</A><br> Friday, January 20, 2006 5:30 AM 1294179 <A HREF=\"/builds/MbUnit-2.3.23.exe\">MbUnit-2.3.23.exe</A><br></pre><hr></body>";
if (html != string.Empty)
{
Regex regRelease = new Regex("HREF\\s*=\\s*(?:\"\"(?<1>[^\"\"]*)\"\"|(?<1>\\S+))");
Regex regDate = new Regex("<br>(.*?)<A HREF");
MatchCollection mclRelease = regRelease.Matches(html);
MatchCollection mclDate = regDate.Matches(html);
if (mclRelease.Count > 0 && mclDate.Count > 0)
{
SortedList list = new SortedList(new Comparer(System.Globalization.CultureInfo.CurrentCulture));
StringBuilder strRelease = new StringBuilder();
StringBuilder strDate = new StringBuilder();
StringBuilder strDownload = new StringBuilder();
int matchCount = 0;
foreach (Match build in mclRelease)
{
string releaseName = build.Value.Replace("HREF=\"", "").Trim();
if (releaseName.Length > 1 && releaseName != "/\">[To")
{
int i = releaseName.IndexOf("\">");
string release = releaseName.Substring(i + 2, releaseName.IndexOf("</A>") - i - 2);
string date = mclDate[matchCount].ToString();
date = date.Replace("<br>", "")
.Replace("<A HREF", "");
date = date.Trim();
date = date.Substring(0, date.LastIndexOf(" "))
.Trim();
DateTime trueDate = Convert.ToDateTime(date);
list.Add(release + " - Released " + trueDate, "<A href=\"" + downloadDir + "/" + release + "\">Download</A>");
matchCount++;
}
}
for (int i = 0; i < list.Count; i++)
{
strRelease.Append(list.GetKey(i) + "<BR />");
strDownload.Append(list.GetByIndex(i) + "<BR />");
strDate.Append("" + "<BR />");
}
releaseOutput.Text = strRelease.ToString();
downloadOutput.Text = strDownload.ToString();
}
}
else
{
releaseOutput.Visible = false;
errorLabel.Visible = true;
}
}
示例9: TestIndexOfKeyBasic
public void TestIndexOfKeyBasic()
{
StringBuilder sblMsg = new StringBuilder(99);
//
SortedList sl2 = null;
StringBuilder sbl3 = new StringBuilder(99);
StringBuilder sbl4 = new StringBuilder(99);
StringBuilder sblWork1 = new StringBuilder(99);
string s1 = null;
string s2 = null;
string s3 = null;
string s4 = null;
int i = 0;
int j = 0;
//
// Constructor: Create SortedList using this as IComparer and default settings.
//
sl2 = new SortedList(this);
// Verify that the SortedList is not null.
Assert.NotNull(sl2);
// Verify that the SortedList is empty.
Assert.Equal(0, sl2.Count);
// boundary
// null key
Assert.Throws<ArgumentNullException>(() =>
{
j = sl2.IndexOfKey((string)null);
}
);
// invalid key
j = sl2.IndexOfKey("No_Such_Key");
Assert.Equal(-1, j);
// Testcase: add few key-val pairs
for (i = 0; i < 100; i++)
{
sblMsg.Length = 0;
sblMsg.Append("key_");
sblMsg.Append(i);
s1 = sblMsg.ToString();
sblMsg.Length = 0;
sblMsg.Append("val_");
sblMsg.Append(i);
s2 = sblMsg.ToString();
sl2.Add(s1, s2);
}
//
// Testcase: test IndexOfKey
//
for (i = 0; i < sl2.Count; i++)
{
sblMsg.Length = 0;
sblMsg.Append("key_"); //key
sblMsg.Append(i);
s1 = sblMsg.ToString();
sblMsg.Length = 0;
sblMsg.Append("val_"); //value
sblMsg.Append(i);
s2 = sblMsg.ToString();
// now use IndexOfKey and IndexOfVal to obtain the same object through GetByIndex and check
s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object
s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object
Assert.True(s3.Equals(s4));
// now Get using the index obtained thru IndexOfKey () and compare it with s2
s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1));
Assert.True(s3.Equals(s2));
}
//
// Remove a key and then check
//
sblMsg.Length = 0;
sblMsg.Append("key_50");
s1 = sblMsg.ToString();
sl2.Remove(s1); //removes "Key_50"
j = sl2.IndexOfKey(s1);
Assert.Equal(-1, j);
}
示例10: runTest
//.........这里部分代码省略.........
break;
}
++iCountTestcases;
if (!sl2.ContainsValue (i))
{
++iCountErrors;
sblMsg.Length = 0 ;
sblMsg.Append( "POINTTOBREAK: Error Err_hd3! -ContainsValue failed at i == " );
sblMsg.Append( i );
Console.Error.WriteLine( sblMsg.ToString() );
break;
}
++iCountTestcases;
try
{
Object o2 = sl2[(Object)(j)];
if (o2 != null)
i2 = (int) o2;
else
{
++iCountErrors;
sblMsg.Length = 0 ;
sblMsg.Append( "POINTTOBREAK: Error Err_9dsh! -Get (Object) failed at i == " );
sblMsg.Append( i );
Console.Error.WriteLine( sblMsg.ToString() );
break;
}
}
catch (Exception exc)
{
Console.Error.WriteLine (exc);
}
strLoc = "Loc_t02hf";
i3 = (int)sl2.GetByIndex(i);
++iCountTestcases;
if ((i3 != i) || (i2 != i))
{
++iCountErrors;
sblMsg.Length = 0 ;
sblMsg.Append( "POINTTOBREAK: Error Err_03dh! - i3 != i; at i == " );
sblMsg.Append( i );
Console.Error.WriteLine( sblMsg.ToString() );
break;
}
}
strLoc="Loc_ugj2";
++iCountTestcases;
dicen = (IDictionaryEnumerator) sl2.GetEnumerator();
++iCountTestcases;
try
{
Object throwaway = dicen.Current;
++iCountErrors;
Console.WriteLine( "Err_001, InvalidOperationException should have been thrown but it was not" );
}
catch (InvalidOperationException)
{}
catch (Exception exc)
{
++iCountErrors;
Console.Error.WriteLine( "POINTTOBREAK: Error Err_1127dh! - " + exc.ToString() );
}
strLoc="Loc_f2aa";
j = 0;
while (dicen.MoveNext())
{
示例11: VisitDocumentElements
internal override void VisitDocumentElements(DocumentElements elements)
{
#if true
// New version without sorted list
int count = elements.Count;
for (int idx = 0; idx < count; ++idx)
{
Paragraph paragraph = elements[idx] as Paragraph;
if (paragraph != null)
{
Paragraph[] paragraphs = paragraph.SplitOnParaBreak();
if (paragraphs != null)
{
foreach (Paragraph para in paragraphs)
{
elements.InsertObject(idx++, para);
++count;
}
elements.RemoveObjectAt(idx--);
--count;
}
}
}
#else
SortedList splitParaList = new SortedList();
for (int idx = 0; idx < elements.Count; ++idx)
{
Paragraph paragraph = elements[idx] as Paragraph;
if (paragraph != null)
{
Paragraph[] paragraphs = paragraph.SplitOnParaBreak();
if (paragraphs != null)
splitParaList.Add(idx, paragraphs);
}
}
int insertedObjects = 0;
for (int idx = 0; idx < splitParaList.Count; ++idx)
{
int insertPosition = (int)splitParaList.GetKey(idx);
Paragraph[] paragraphs = (Paragraph[])splitParaList.GetByIndex(idx);
foreach (Paragraph paragraph in paragraphs)
{
elements.InsertObject(insertPosition + insertedObjects, paragraph);
++insertedObjects;
}
elements.RemoveObjectAt(insertPosition + insertedObjects);
--insertedObjects;
}
#endif
}
示例12: setPositions
public void setPositions(SortedList p)
{
positions.Clear();
foreach (PedestrianPosition ped in p.Values) {
positions.AddLast(ped);
}
PedestrianPosition pos = (PedestrianPosition)p.GetByIndex (0);
transform.position = new Vector3 (pos.getX(), 0, pos.getY());
}
示例13: Test01
public void Test01()
{
SortedList slst1;
Int32 iNumberOfElements;
String strValue;
Array ar1;
// ctor(Int32)
iNumberOfElements = 10;
slst1 = new SortedList(iNumberOfElements);
for (int i = iNumberOfElements - 1; i >= 0; i--)
{
slst1.Add(50 + i, "Value_" + i);
}
Assert.Equal(slst1.Count, iNumberOfElements);
//we will assume that all the keys are sorted as the name implies. lets see
//We intially filled this lit with descending and much higher keys. now we access the keys through index
for (int i = 0; i < slst1.Count; i++)
{
strValue = "Value_" + i;
Assert.Equal(strValue, slst1[slst1.GetKey(i)]);
}
//paramter stuff
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
iNumberOfElements = -5;
slst1 = new SortedList(iNumberOfElements);
}
);
slst1 = new SortedList();
Assert.Throws<ArgumentNullException>(() =>
{
slst1.Add(null, 5);
}
);
iNumberOfElements = 10;
slst1 = new SortedList();
for (int i = iNumberOfElements - 1; i >= 0; i--)
{
slst1.Add(i, null);
}
for (int i = 0; i < slst1.Count; i++)
{
strValue = "Value_" + i;
Assert.Null(slst1.GetByIndex(i));
}
//Contains()
iNumberOfElements = 10;
slst1 = new SortedList(iNumberOfElements);
for (int i = iNumberOfElements - 1; i >= 0; i--)
{
slst1.Add(50 + i, "Value_" + i);
}
for (int i = 0; i < slst1.Count; i++)
{
strValue = "Value_" + i;
Assert.True(slst1.Contains(50 + i));
}
Assert.False(slst1.Contains(1));
Assert.False(slst1.Contains(-1));
//paramter stuff
Assert.Throws<ArgumentNullException>(() =>
{
slst1.Contains(null);
}
);
//get/set_Item
slst1 = new SortedList();
for (int i = iNumberOfElements - 1; i >= 0; i--)
{
slst1[50 + i] = "Value_" + i;
}
Assert.Equal(slst1.Count, iNumberOfElements);
for (int i = 0; i < slst1.Count; i++)
{
strValue = "Value_" + i;
Assert.Equal(strValue, slst1[i + 50]);
}
//already existent ones
strValue = "Value_1";
Assert.Equal(strValue, slst1[51]);
strValue = "Different value";
slst1[51] = strValue;
//.........这里部分代码省略.........
示例14: Ctor_IDictionary_IComparer
public static void Ctor_IDictionary_IComparer(int count, bool sorted)
{
var hashtable = new Hashtable();
if (sorted)
{
// Create a hashtable in the correctly sorted order
for (int i = count - 1; i >= 0; i--)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
else
{
// Create a hashtable in the wrong order and make sure it is sorted
for (int i = 0; i < count; i++)
{
hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2"));
}
}
var sortList = new SortedList(hashtable, new CustomComparer());
Assert.Equal(count, sortList.Count);
Assert.True(sortList.Capacity >= sortList.Count);
for (int i = 0; i < count; i++)
{
string key = "Key_" + i.ToString("D2");
string value = "Value_" + i.ToString("D2");
string expectedValue = "Value_" + (count - i - 1).ToString("D2");
Assert.Equal(sortList.GetByIndex(i), expectedValue);
Assert.Equal(hashtable[key], sortList[key]);
}
Assert.False(sortList.IsFixedSize);
Assert.False(sortList.IsReadOnly);
Assert.False(sortList.IsSynchronized);
}
示例15: runTest
//.........这里部分代码省略.........
table.Add(",", ",");
table.Add("/", "/");
table.Add("-", "-");
table.Add(" ", " ");
table.Add("~", "~");
table.Add(" ", " ");
random = new Random();
numberOfRounds = random.Next(100, 10000);
formatString = String.Empty;expectedValue = String.Empty;
for(int i=0; i<numberOfRounds; i++){
returnedValue=String.Empty;
try{
numberOfStringConcats = random.Next(1, 20);
builder1 = new StringBuilder();
builder2 = new StringBuilder();
previous = String.Empty;
for(int j=0; j<numberOfStringConcats; j++){
do{
i1 = random.Next(table.Count);
temp = (String)table.GetKey(i1);
getOut = true;
if(j!=0){
if(temp.Length>previous.Length){
if(temp.EndsWith(previous))
getOut = false;
}else{
if(previous.EndsWith(temp))
getOut = false;
}
}
}while(!getOut);
previous = temp;
builder1.Append(temp);
temp1 = (String)table.GetByIndex(i1);
builder2.Append(temp1);
if((String)table[temp] != temp1)
throw new Exception("Loc_7432edgs! What is happening here? " + temp + " " + temp1);
}
formatString = builder1.ToString();
if(formatString.Length==1){
i--;
continue;
}
expectedValue = builder2.ToString();
returnedValue = date.ToString(formatString);
if(!returnedValue.Equals(expectedValue)){
iCountErrors++;
Console.WriteLine("Err_87sdg! Format: {0}, Returned: {1}, Expected: {2}", formatString, returnedValue, expectedValue);
}
}catch(Exception){
Console.WriteLine("Err_EDfdfd! Exception thrown, Format: {0}, Returned: {1}, Expected: {2}", formatString, returnedValue, expectedValue);
}
}
strLoc = "Loc_97345sdg";
iCountTestcases++;
formatString = null;
returnedValue = date.ToString(formatString);
if(!returnedValue.Equals(expectedFormalValues[5])){
iCountErrors++;
Console.WriteLine("Err_753gfs! Unexpcted value returned, " + returnedValue);
}
strLoc = "Loc_34975sgd";
iCountTestcases++;
formatString = String.Empty;
returnedValue = date.ToString(formatString);
if(!returnedValue.Equals(expectedFormalValues[5])){