本文整理汇总了C#中SortedDictionary.Clear方法的典型用法代码示例。如果您正苦于以下问题:C# SortedDictionary.Clear方法的具体用法?C# SortedDictionary.Clear怎么用?C# SortedDictionary.Clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedDictionary
的用法示例。
在下文中一共展示了SortedDictionary.Clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Process
public MeshContent Process()
{
newMesh = new MeshContent();
newMesh.Name = splitter.mesh.Name + splitter.currentIndex.ToString();
SortedDictionary<string, object> faceBones = new SortedDictionary<string, object>();
GeometryContent newGeom = new GeometryContent();
while (index < geom.Indices.Count - 1)
{
int[] faceIndices = new int[]
{
geom.Indices[index],
geom.Indices[index+1],
geom.Indices[index+2]
};
for (int i = 0; i < 3; i++)
{
BoneWeightCollection weightCollection = weightChannel[
geom.Indices[index + i]];
foreach (BoneWeight weight in weightCollection)
{
if (!meshBones.ContainsKey(weight.BoneName) &&
!faceBones.ContainsKey(weight.BoneName))
faceBones.Add(weight.BoneName, null);
}
}
if (meshBones.Count + faceBones.Count > splitter.maxBones)
{
faceBones.Clear();
vertexEndIndex = index;
break;
}
foreach (string s in faceBones.Keys)
meshBones.Add(s, null);
faceBones.Clear();
for (int i = 0; i < 3; i++)
{
if (oldToNewDict.ContainsKey(faceIndices[i]))
{
}
else
{
int newIndex = newMesh.Positions.Count;
newMesh.Positions.Add(geom.Vertices.Positions[faceIndices[i]]);
oldToNewDict.Add(faceIndices[i], newIndex);
newGeom.Vertices.Add(newIndex);
}
newGeom.Indices.Add(oldToNewDict[faceIndices[i]]);
}
index += 3;
vertexEndIndex = index;
}
newMesh.Geometry.Add(newGeom);
Finish();
return newMesh;
}
示例2: OnWizardOtherButton
void OnWizardOtherButton()
{
GameObject gameObject = Selection.activeGameObject;
if (gameObject == null || resultCubemap == null) return;
Vector3 tmpPos = cameraViewPort.transform.position;
Quaternion tmpRot = cameraViewPort.transform.rotation;
GameObject player = SingletonNames.getPlayer();
player.SetActive(false);
SortedDictionary<Camera, bool> visibles = new SortedDictionary<Camera, bool>();
foreach (Camera c in Camera.allCameras) {
if (c != cameraViewPort) {
visibles.Add(c, c.enabled);
c.enabled = false;
}
}
cameraViewPort.transform.position = gameObject.transform.position;
cameraViewPort.transform.rotation = gameObject.transform.rotation;
cameraViewPort.RenderToCubemap(resultCubemap);
foreach (Camera c in Camera.allCameras)
c.enabled = visibles[c];
visibles.Clear();
visibles = null;
player.SetActive(true);
cameraViewPort.transform.position = tmpPos;
cameraViewPort.transform.rotation = tmpRot;
}
示例3: LengthOfLongestSubstring
public int LengthOfLongestSubstring(string s)
{
SortedDictionary<char, int> map = new SortedDictionary<char, int>();
// Dictionary to maintain the substrings.
SortedDictionary<string, int> ss = new SortedDictionary<string,int>();
char[] chArr = s.ToCharArray();
StringBuilder sb = new StringBuilder();
foreach(char c in chArr)
{
if(!map.ContainsKey(c))
{
map.Add(c,1);
sb.Append(c);
}
else
{
if (!ss.ContainsKey(sb.ToString()))
{
ss.Add(sb.ToString(), sb.ToString().Length);
}
sb.Clear();
map.Clear();
}
}
var s1 = ss.Keys.ElementAt(0);
Console.WriteLine(s1);
return ss.Values.Max();
}
示例4: Main
private static void Main(string[] args)
{
ConsistentHash<string> chash = new ConsistentHash<string>();
Console.WriteLine("Adding 10 servers.");
for (int i = 0; i < 10; i++) {
chash.Add("server"+i);
}
Console.WriteLine("Key distributions:");
var counts = new SortedDictionary<string, int>();
for (int i = 0; i < 1000; i++) {
var key = "key"+i;
var server = chash.GetNext(key);
if (!counts.ContainsKey(server)) {
counts[server] = 0;
}
counts[server]++;
}
foreach (var server in counts.Keys) {
Console.WriteLine("There are {0} keys assigned to {1}", counts[server], server);
}
Console.WriteLine("Adding 1 more server.");
chash.Add("serverX");
Console.WriteLine("New key distributions:");
counts.Clear();
for (int i = 0; i < 1000; i++) {
var key = "key"+i;
var server = chash.GetNext(key);
if (!counts.ContainsKey(server)) {
counts[server] = 0;
}
counts[server]++;
}
foreach (var server in counts.Keys) {
Console.WriteLine("There are {0} keys assigned to {1}", counts[server], server);
}
}
示例5: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
string openIdType = "hishop.plugins.openid.alipay.alipayservice";
OpenIdSettingsInfo openIdSettings = OpenIdHelper.GetOpenIdSettings(openIdType);
if (openIdSettings != null)
{
string alipaytoken = Request.QueryString["alipaytoken"];
XmlDocument document = new XmlDocument();
document.LoadXml(Cryptographer.Decrypt(openIdSettings.Settings));
SortedDictionary<string, string> dicArrayPre = new SortedDictionary<string, string>();
dicArrayPre.Add("service", "user.logistics.address.query");
dicArrayPre.Add("partner", document.FirstChild.SelectSingleNode("Partner").InnerText);
dicArrayPre.Add("_input_charset", "utf-8");
dicArrayPre.Add("return_url", Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("LogisticsAddress_url")));
dicArrayPre.Add("token", alipaytoken);
Dictionary<string, string> dicArray = OpenIdFunction.FilterPara(dicArrayPre);
string sign = OpenIdFunction.BuildMysign(dicArray, document.FirstChild.SelectSingleNode("Key").InnerText, "MD5", "utf-8");
dicArray.Add("sign", sign);
dicArray.Add("sign_type", "MD5");
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, string> pair in dicArray)
{
builder.Append(OpenIdFunction.CreateField(pair.Key, pair.Value));
}
dicArrayPre.Clear();
dicArray.Clear();
OpenIdFunction.Submit(OpenIdFunction.CreateForm(builder.ToString(), "https://mapi.alipay.com/gateway.do?_input_charset=utf-8"));
}
}
示例6: RunTest
private static void RunTest(SortedDictionary<int, User> sortedDict, SortedSet<User> sortedSet, IEnumerable<int> testSizes,
string label,
Func<SortedDictionary<int, User>, int, TimeSpan> testFuncSoretdDict, Func<SortedSet<User>, int, TimeSpan> testFuncSortedSet)
{
foreach (int test in testSizes)
{
var result = testFuncSoretdDict(sortedDict, test);
Console.WriteLine("{0} with Sorted Dictionary ({1}): {2}", label, test, result);
result = testFuncSortedSet(sortedSet, test);
Console.WriteLine("{0} with Sorted Set ({1}): {2}", label, test, result);
sortedDict.Clear();
sortedSet.Clear();
Console.WriteLine();
}
}
示例7: ProcessFile
private static void ProcessFile(String filePath)
{
Console.WriteLine("Processing file...\n");
// Using SortedDictionary<TKey, TValue> which uses Binary Search Tree [O(log N)] and have [O(log N)] for inserts and removals
var concordance = new SortedDictionary<String, List<Int32>>();
using (var streamReader = new StreamReader(filePath))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
ProcessText(line, concordance);
}
}
PrintConcordance(concordance);
// Release resources
concordance.Clear();
}
示例8: Main
static void Main(string[] args)
{
var dictionary = new SortedDictionary<int,int>();
var array = new int[] {3, 4, 4, -2, 3, 3, 4, 3, -2};
foreach (var item in array)
{
int count = 1;
if(dictionary.ContainsKey(item))
{
count = dictionary[item] + 1;
}
dictionary[item] = count;
}
foreach (var pair in dictionary)
{
Console.WriteLine("{0} - > {1}",pair.Key,pair.Value);
}
dictionary.Clear();
var dict = new Dictionary<string, int>();
var inputStrings= new string[]{"C#", "SQL", "PHP", "PHP", "SQL", "SQL"};
foreach (var item in inputStrings)
{
int count = 1;
if (dict.ContainsKey(item))
{
count = dict[item] + 1;
}
dict[item] = count;
}
var list = new List<int>() { 3, 4, 4, -2, 3, 3, 4, 3, -2 };
var sorted = list.GroupBy(x => x).OrderBy(x => x.Count());
var onlyoddcountlist = inputStrings.GroupBy(x => x.ToLower()).OrderBy(x => x.Count()).Where(x => x.Count() % 2 == 1);
var input = "This is the TEXT. Text, text, text – THIS TEXT! Is this the text?";
var dic = input.Split(new char[] { ' ', ',', '?', '!', '–', '.' }).GroupBy(x => x.ToLower()).ToDictionary(g => g.Key, g => g.Count());
}
示例9: RunTestOneSortedDict
/// <summary>
/// adds several items to a collection, then searches for items in that collection. The test is repeated 50 times to get a more consistent result
/// </summary>
/// <param name="collection"></param>
/// <param name="numItemsToTest"></param>
/// <returns></returns>
static TimeSpan RunTestOneSortedDict(SortedDictionary<int, User> collection, int numItemsToTest)
{
Stopwatch timer = new Stopwatch();
timer.Start();
// perform the test 50 times:
for (int counter = 0; counter < 50; counter++)
{
collection.Clear();
// add some random items
Random rnd = new Random();
var sequence = from n in Enumerable.Range(1, numItemsToTest)
select rnd.Next() * n;
foreach (var item in sequence)
{
int i = item;
while (collection.ContainsKey(i) && i < numItemsToTest * 2)
i += 1;
if(!collection.ContainsKey(i))
collection.Add(i, new User(i, "family", "name"));
}
// search for 1000 random items
var sequence2 = from n in Enumerable.Range(1, 1000)
select rnd.Next() * n;
bool found = false;
foreach (var item in sequence2)
{
// This method is an O(log n) operation.
found &= collection.ContainsKey(item);
}
}
timer.Stop();
return timer.Elapsed;
}
示例10: SortSystems
/// <summary>
/// SortSystems
/// </summary>
public void SortSystems()
{
SortedDictionary<string, EcellObject> tempDic = new SortedDictionary<string, EcellObject>();
List<EcellObject> systemList = null;
foreach (KeyValuePair<string, List<EcellObject>> systemDic in m_systemDic)
{
tempDic.Clear();
systemList = systemDic.Value;
foreach (EcellObject system in systemList)
tempDic.Add(system.Key, system);
systemList.Clear();
foreach (EcellObject system in tempDic.Values)
systemList.Add(system);
}
}
示例11: ProcessLog
//.........这里部分代码省略.........
// keep track of line no
int a = 0;
log.Info("ProcessLog start " + (GC.GetTotalMemory(false) / 1024.0 / 1024.0));
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
a++;
if (a % 100 == 0)
Console.Write(a + "\r");
string strLine = line.Replace(", ", ",");
strLine = strLine.Replace(": ", ":");
string[] items = strLine.Split(',', ':');
// process the fmt messages
if (line.StartsWith("FMT"))
{
// +1 for line no
string[] names = new string[items.Length - 5 + 1];
names[0] = "LineNo";
Array.ConstrainedCopy(items, 5, names, 1, names.Length - 1);
MLArray format = CreateCellArray(items[3] + "_label", names);
if (items[3] == "PARM")
{
}
else
{
mlList.Add(format);
}
len[items[3]] = names.Length;
} // process param messages
else if (line.StartsWith("PARM"))
{
try
{
param[items[1]] = double.Parse(items[2], CultureInfo.InvariantCulture);
}
catch { }
}// everyting else is generic
else
{
// make sure the line is long enough
if (items.Length < 2)
continue;
// check we have a valid fmt message for this message type
if (!len.ContainsKey(items[0]))
continue;
// check the fmt length matchs what the log has
if (items.Length != (int)len[items[0]])
continue;
// make it as being seen
seen[items[0]] = 1;
double[] dbarray = new double[items.Length];
// set line no
dbarray[0] = a;
for (int n = 1; n < items.Length; n++)
{
try
{
dbarray[n] = double.Parse(items[n], CultureInfo.InvariantCulture);
}
catch { }
}
if (!data.ContainsKey(items[0]))
data[items[0]] = new DoubleList();
data[items[0]].Add(dbarray);
}
// split at x records
if (a % 2000000 == 0)
{
GC.Collect();
DoWrite(fn + "-" + a, data, param, mlList, seen);
mlList.Clear();
data.Clear();
param.Clear();
seen.Clear();
GC.Collect();
}
}
DoWrite(fn + "-" + a, data, param, mlList, seen);
sr.Close();
}
示例12: DoFirstAllocation
protected bool DoFirstAllocation(int depositSize)
{
SortedDictionary<string, Planet> sites = new SortedDictionary<string, Planet>();
foreach (Planet firstPlanet in this.shuffledPlanets)
{
List<Planet> rotatedPlanets = new List<Planet>(this.shuffledPlanets);
rotatedPlanets.RemoveRange(0, shuffledPlanets.IndexOf(firstPlanet));
rotatedPlanets.AddRange(shuffledPlanets.GetRange(0, shuffledPlanets.IndexOf(firstPlanet)));
sites.Clear();
foreach (string res in this.shuffledResources)
{
Planet testSite = rotatedPlanets.FirstOrDefault((p) =>
{
return (p.CanAcceptStrategicResource(res) && !sites.Values.Contains(p));
});
if (null == testSite)
{
testSite = rotatedPlanets.FirstOrDefault((p) =>
{
return !sites.Values.Contains(p);
});
}
if (null != testSite) sites.Add(res, testSite);
}
if (sites.Keys.Count == this.shuffledResources.Count)
{
foreach (string res in this.shuffledResources)
{
sites[res].resource = new ResourceDeposit(res, depositSize, ResourceDeposit.ResourceType.Strategic);
this.shuffledPlanets.Remove(sites[res]);
this.remainingQuantities[res] -= depositSize;
}
return true;
}
}
return false;
}
示例13: button4_Click
private void button4_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
Stopwatch sw = new Stopwatch();
TimeSpan slTime = TimeSpan.MinValue;
TimeSpan treeTime = TimeSpan.MaxValue;
Random rng = new Random();
SortedDictionary<int, int> sl = new SortedDictionary<int, int>();
RedBlackTree<int, int> tree = new RedBlackTree<int, int>();
sb.Append("1 tick = ");
sb.Append((int)(1000000000d / ((double)Stopwatch.Frequency)));
sb.AppendLine(" nano seconds");
sb.AppendLine(" Entries | SL in ms | RBT adj || SL ticks | RBT adj | % Time Spent");
const long MaxRotations = 1000;
const long MinInsert = 99999;
const long MaxInsert = 100000;
long[,] slData = new long[MaxInsert - MinInsert + 1, MaxRotations];
long[,] treeData = new long[MaxInsert - MinInsert + 1, MaxRotations];
double[] slData2 = new double[MaxInsert - MinInsert + 1];
double[] treeData2 = new double[MaxInsert - MinInsert + 1];
for (long j = MinInsert; j <= MaxInsert; j++)
for (long k = 0L; k < MaxRotations; k++)
{
sl.Clear();
tree.Clear();
int rngValue = rng.Next();
sw.Start();
for (int i = 0; i < j; i++)
sl[rngValue] = rngValue;
sw.Stop();
slTime = sw.Elapsed;
sw.Reset();
sw.Start();
for (int i = 0; i < j; i++)
tree.Insert(rngValue, rngValue, true);
sw.Stop();
treeTime = sw.Elapsed;
sw.Reset();
slData[j - MinInsert, k] = slTime.Ticks;
treeData[j - MinInsert, k] = treeTime.Ticks;
}
for (long j = MinInsert; j <= MaxInsert; j++)
{
long slSum = 0, treeSum = 0;
for (int k = 0; k < MaxRotations; k++)
{
slSum += slData[j - MinInsert, k];
treeSum += treeData[j - MinInsert, k];
}
slData2[j - MinInsert] = (double)slSum / (double)MaxRotations;
treeData2[j - MinInsert] = (double)treeSum / (double)MaxRotations;
}
for (long j = MinInsert; j <= MaxInsert; j++)
{
sb.Append(j.ToString().PadLeft(8));
sb.Append(" |");
sb.Append(string.Empty.PadLeft(9));
sb.Append(" |");
sb.Append(string.Empty.PadLeft(8));
sb.Append(" ||");
sb.Append(slData2[j - MinInsert].ToString("F2").PadLeft(9));
sb.Append(" |");
sb.Append((treeData2[j - MinInsert] - slData2[j - MinInsert]).ToString("F2").PadLeft(8));
sb.Append(" |");
sb.Append((treeData2[j - MinInsert] / slData2[j - MinInsert] * 100d).ToString("F2").PadLeft(13));
sb.AppendLine();
}
tbOut.Text = sb.ToString();
}
示例14: set_values_impl
// important: we visually sort them!
private void set_values_impl(Dictionary< string, int> values, bool finished, bool snooped_all_rows) {
too_many_distinct_values_ = values.Count > max_distinct_values_count;
finished_ = finished;
snooped_all_rows_ = snooped_all_rows;
while (values.Count > max_distinct_values_count) {
int min = values.Values.Min();
var erase = values.First(x => x.Value == min).Key;
values.Remove(erase);
}
list.SuspendLayout();
int sel = list.SelectedIndex;
string former_sel = "";
if (sel >= 0)
former_sel = (list.GetItem(sel).RowObject as snoop_item).value;
// find out the existing items
SortedDictionary<string,int> value_to_index = new SortedDictionary<string, int>(StringComparer.InvariantCultureIgnoreCase);
// just in case we're snooping, and there was a former snoop - we keep existing entries...
// but, when the snoop is over, anything that found 0 results, is removed from the list
int values_contain_existing_count = 0;
for (int idx = 0; idx < list.GetItemCount(); ++idx) {
var value = (list.GetItem(idx).RowObject as snoop_item).value;
if (values.ContainsKey(value))
++values_contain_existing_count;
value_to_index.Add(value, idx);
}
if (finished && values.Count > values_contain_existing_count) {
// there were some rows with "zero" count - remove them completely
list.Items.Clear();
value_to_index.Clear();
}
foreach( string value in values.Keys)
if ( !value_to_index.ContainsKey(value))
value_to_index.Add(value, -1);
// snooped_all_rows - if false, we always append "+" to the count. Otherwise, we print only the count
int offset = 0;
int new_sel_idx = -1;
foreach ( var val_and_idx in value_to_index) {
string value = val_and_idx.Key;
int count = values.ContainsKey(value) ? values[value] : 0;
if (val_and_idx.Value < 0)
list.InsertObjects(offset, new[] {new snoop_item() } );
var i = list.GetItem(offset).RowObject as snoop_item;
i.number = offset + 1;
i.value = value;
i.count = "" + count + (finished && snooped_all_rows ? "" : "+");
if (value == former_sel)
new_sel_idx = offset;
list.RefreshObject(i);
++offset;
}
if (new_sel_idx >= 0)
list.SelectedIndex = new_sel_idx;
list.ResumeLayout(true);
}
示例15: GetAllMethods
/// <summary>
/// Iterator method to enumerate all the methods and constructors defined in an assembly
/// </summary>
/// <param name="asm">The assembly to inspect</param>
/// <returns>Each method/constructor defined in the specified assembly</returns>
private IEnumerable<MethodData> GetAllMethods(string assemblyPath)
{
//using (var manager = new AssemblyReflectionManager())
//{
// if (manager.LoadAssembly(assemblyPath, "TempDomain"))
// {
// var results = manager.Reflect<IEnumerable<MethodData>>((asm) =>
// {
try
{
_assembly = Assembly.ReflectionOnlyLoad(File.ReadAllBytes(assemblyPath));
_loadedAssembly.Add(_assembly.FullName);
}
catch (FileLoadException ex)
{
foreach (var ass in AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies())
{
if (_loadedAssembly.Contains(ass.FullName))
{
_assembly = ass;
break;
}
}
}
List<MethodData> mBase = new List<MethodData>();
SortedDictionary<int, bool> tokenSeenSet = new SortedDictionary<int, bool>();
BindingFlags allDeclared = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (Module mod in _assembly.GetModules(false))
{
// First return all module-global methods
foreach (MethodInfo meth in mod.GetMethods(allDeclared))
{
Debug.Assert(meth.MetadataToken >> 24 == 0x6, "Got a method token which wasn't a MethodDef");
Debug.Assert(!tokenSeenSet.ContainsKey(meth.MetadataToken), "Saw the same method token more than once");
tokenSeenSet.Add(meth.MetadataToken, true);
mBase.Add(new MethodData(meth));
}
// Now loop through each type. Note that this includes nested types.
foreach (Type type in mod.GetTypes())
{
// Return each constructor
foreach (ConstructorInfo con in type.GetConstructors(allDeclared))
{
Debug.Assert(con.MetadataToken >> 24 == 0x6, "Got a method token which wasn't a MethodDef");
Debug.Assert(!tokenSeenSet.ContainsKey(con.MetadataToken), "Saw the same method token more than once");
tokenSeenSet.Add(con.MetadataToken, true);
mBase.Add(new MethodData(con));
}
// Return each method.
// Note that this includes methods that are special in C# like property getters
foreach (MethodInfo meth in type.GetMethods(allDeclared))
{
Debug.Assert(meth.MetadataToken >> 24 == 0x6, "Got a method token which wasn't a MethodDef");
Debug.Assert(!tokenSeenSet.ContainsKey(meth.MetadataToken), "Saw the same method token more than once");
tokenSeenSet.Add(meth.MetadataToken, true);
mBase.Add(new MethodData(meth));
}
}
// Now sanity-check that we haven't missed any methods by looking for gaps in the token list
// Unfortunately we have no easy way to check that there aren't any extra methods at the end.
// Tokens are scoped to a module, so we track usage on a per-module basis
int lastTok = 0x06000000;
foreach (int tok in tokenSeenSet.Keys)
{
Debug.Assert(tok > lastTok, "token list is supposed to be sorted");
Debug.Assert(tok == lastTok + 1, "missed some method tokens",
String.Format("Missed 0x{0:x} to 0x{0:x}", lastTok + 1, tok));
lastTok = tok;
}
tokenSeenSet.Clear();
}
return mBase;
// });
// return results;
// }
//}
//return new List<MethodData>();
}