public static void Main(string[] args) { System.IO.StreamReader reader = OpenInput(args); int numLines = System.Int32.Parse(reader.ReadLine()); System.Collections.Generic.SortedList<int, string> longest = new System.Collections.Generic.SortedList<int, string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line == null) continue; if (longest.Count < numLines) { longest.Add(line.Length, line); } else if (line.Length > longest.Keys[0]) { // We need to add this line and push out the extra that's smallest in our list longest.Add(line.Length, line); longest.RemoveAt(0); } } System.Collections.Generic.IList<int> keys = longest.Keys; for (int i = keys.Count - 1; i >= 0; --i) { System.Console.WriteLine(longest[keys[i]]); } }
protected void Page_Load(object sender, EventArgs e) { string tempurl = Utils.GetStaticPageNumbersHtml(2, 100, "showforum", ".aspx", 8); DbParameter[] prams = { DbHelper.MakeInParam("@name", DbType.String, 3,"aabbccdd") }; DbHelper.ExecuteNonQuery(CommandType.Text, "INSERT INTO itca_test(name) VALUES (@name)", prams); DbDataReader dr = DbHelper.ExecuteReader(CommandType.Text, "SELECT * FROM wy_articles"); while (dr.Read()) { Response.Write(dr["title"].ToString()+"<br />"+ dr["content"].ToString()); } if (Request.QueryString["a"] != null) { Response.Write(Request.QueryString["a"].ToString()); } TinyCache tc = new TinyCache(); tc.AddObject("test", "bbbbb"); Response.Write("TinyCache:" + tc.RetrieveObject("test") as string); System.Collections.Generic.SortedList<int, object> list = new System.Collections.Generic.SortedList<int, object>(); list.Add(1, "协会公告"); list.Add(2, "协会新闻"); object aaaa = list[1]; }
protected void Page_Load(object sender, EventArgs e) { string tempurl = Utils.GetStaticPageNumbersHtml(2, 100, "showforum", ".aspx", 8); DbParameter[] prams = { DbHelper.MakeInParam("@name", DbType.String, 3, "aabbccdd") }; DbHelper.ExecuteNonQuery(CommandType.Text, "INSERT INTO itca_test(name) VALUES (@name)", prams); DbDataReader dr = DbHelper.ExecuteReader(CommandType.Text, "SELECT * FROM wy_articles"); while (dr.Read()) { Response.Write(dr["title"].ToString() + "<br />" + dr["content"].ToString()); } if (Request.QueryString["a"] != null) { Response.Write(Request.QueryString["a"].ToString()); } TinyCache tc = new TinyCache(); tc.AddObject("test", "bbbbb"); Response.Write("TinyCache:" + tc.RetrieveObject("test") as string); System.Collections.Generic.SortedList <int, object> list = new System.Collections.Generic.SortedList <int, object>(); list.Add(1, "协会公告"); list.Add(2, "协会新闻"); object aaaa = list[1]; }
public void UpdateKey(TKey oldKey, TKey newKey) { var item = FSortedList[oldKey]; FSortedList.Remove(oldKey); FSortedList.Add(newKey, item); OnOrderChanged(); }
/// <summary> /// If key doesnt exist it will be added and value will be set to default. /// If it exist default value will be changed. /// </summary> /// <param name="key">Key identifier</param> /// <param name="obj">object that you want to set as the default value</param> public void SetDefault(int key, object obj) { if (!list.ContainsKey(key)) { SettingItem item = new SettingItem(obj); item.Key = key; item.UpdatedSetting += new FmdcEventHandler(item_UpdatedSetting); list.Add(key, item); } else { list[key].DefaultValue = obj; } }
internal object this[int index] { get { if (m_datalist.ContainsKey(index)) { return(m_datalist[index]); } else { return(null); } } set { if (m_datalist.ContainsKey(index)) { m_datalist[index] = value; } else { m_datalist.Add(index, value); } } }
public static bool detCursorSelection(Canvas rel, Point relPos, out UIElement result) { var list = new System.Collections.Generic.SortedList<int, UIElement>(); foreach (UIElement ue in rel.Children) { var ta = ue.TransformToAncestor(rel); var p = ta.Transform(new Point(0, 0)); var r = new Rect(p, ue.RenderSize); if (r.Contains(relPos)) try { list.Add(Canvas.GetZIndex(ue), ue); } catch (Exception) { } } if (list.Count != 0) { var pr = list.Keys.Max(); result = list[pr]; return true; } else { result = null; return false; } }
/// <summary> /// Sort the index of SequenceAlignmentMap by RName then by Pos. /// Fill the index (sorted by RName then by Pos) into a list, when the list size reaches /// the maximum limit, write the list to file and clear the list. /// </summary> private SortedDictionary <string, IList <string> > SortByChromosomeCoordinates() { SortedDictionary <string, IList <string> > sortedFiles = new SortedDictionary <string, IList <string> >(); IList <string> files = null; var groups = new System.Collections.Generic.SortedList <string, System.Collections.Generic.SortedList <object, string> >(); System.Collections.Generic.SortedList <object, string> sortedList = null; for (int index = 0; index < sequenceAlignMap.QuerySequences.Count; index++) { SAMAlignedSequence alignedSeq = sequenceAlignMap.QuerySequences[index]; if (!groups.TryGetValue(alignedSeq.RName, out sortedList)) { sortedList = new System.Collections.Generic.SortedList <object, string>(); groups.Add(alignedSeq.RName, sortedList); } string indices = string.Empty; if (!sortedList.TryGetValue(alignedSeq.Pos, out indices)) { sortedList.Add(alignedSeq.Pos, index.ToString(CultureInfo.InvariantCulture)); } else { indices = string.Format(CultureInfo.InvariantCulture, "{0},{1}", indices, index.ToString(CultureInfo.InvariantCulture)); sortedList[alignedSeq.Pos] = indices; } if (sortedList.Count >= SortedListMaxCount) { if (!sortedFiles.TryGetValue(alignedSeq.RName, out files)) { files = new List <string>(); sortedFiles.Add(alignedSeq.RName, files); } files.Add(WriteToFile(sortedList)); sortedList.Clear(); } } foreach (KeyValuePair <string, System.Collections.Generic.SortedList <object, string> > group in groups) { if (group.Value.Count > 0) { if (!sortedFiles.TryGetValue(group.Key, out files)) { files = new List <string>(); sortedFiles.Add(group.Key, files); } files.Add(WriteToFile(group.Value)); group.Value.Clear(); } } return(sortedFiles); }
/// <summary> /// 方法:初始化(覆写实现) /// </summary> public override void DoIni() { try { if (_cameraList != null && _cameraList.Count > 0) { for (int i = 0; i < _cameraList.Count; i++) { ProDriver.APIHandle.CameraAPIHandle camAPI = new ProDriver.APIHandle.CameraAPIHandle(_cameraList[i]); camAPI.ImageGrabbedEvt += Device_Camera_ImageGrabbedEvt; CamHandleList.Add(_cameraList[i].ID, camAPI); _camGrabbedList.Add(_cameraList[i].ID, false); if (!_cameraList[i].IsConnected) { CamHandleList[_cameraList[i].ID].EnumerateCameraList(); //枚举相机列表 if (CamHandleList[_cameraList[i].ID].GetCameraBySN(_cameraList[i].SerialNo)) { if (!CamHandleList[_cameraList[i].ID].Open()) { if (!_timer.Enabled) { StartTimer(); //第一连接失败,需要启动定时器,因为相机连接状态更新的值与原来的值一样,不会触发属性值改变事件 } return; } else { _cameraList[i].IsActive = true; _cameraList[i].IsConnected = true; } } else { continue; } } } if (!_isCameraInitialized) { InitCamera(); _isCameraInitialized = true; InitVisionLogic(); } } } catch (Exception ex) { //ProCommon.Communal.LogWriter.WriteException(_exLogFilePath, ex); //ProCommon.Communal.LogWriter.WriteLog(_sysLogFilePath, string.Format("错误:初始化相机设备失败!\n异常描述:{0}", ex.Message)); //throw new ProCommon.Communal.InitException(ToString(), "初始化异常\n" + ex.Message); } }
public SortedEditableList(System.Collections.Generic.IList <T> list, Func <T, TKey> keySelector) : base(list) { FSortedList = new System.Collections.Generic.SortedList <TKey, T>(); FKeySelector = keySelector; foreach (var item in list) { FSortedList.Add(FKeySelector(item), item); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); MySqlConnection con = new MySqlConnection("Server=127.0.0.1;Database=dht;Uid=dht;Pwd=sgv54hnf3ha142s3dfg4ad5sh;"); con.Open(); try { MySqlCommand cmd = new MySqlCommand("SELECT MAX(id) AS max_id , MIN(id) AS min_id FROM nodes", con); IDataReader r; r = cmd.ExecuteReader(CommandBehavior.SingleRow); if (!r.Read()) { return; } long max = r.GetInt64(0); long min = r.GetInt64(1); r.Close(); cmd.CommandText = "SELECT id, endpoint FROM nodes WHERE id >= @id and lastupdate>(subtime(CURRENT_TIMESTAMP,'05:00:00')) order by id LIMIT 0,1"; cmd.Parameters.Add("@id", MySqlDbType.Int64); System.Random rnd = new System.Random(); System.Collections.Generic.SortedList <long, string> l = new System.Collections.Generic.SortedList <long, string> (); System.Collections.Generic.List <string> l2 = new System.Collections.Generic.List <string> (); int i; for (i = 0; i < 10; i++) { long id = getrand(rnd, min, max); //Response.Output.WriteLine (id); cmd.Parameters [0].Value = id; r = cmd.ExecuteReader(CommandBehavior.SingleRow); try { if (!r.Read()) { continue; } try { l.Add(r.GetInt64(0), r.GetString(1)); l2.Add(r.GetString(1)); } catch { } } finally { r.Close(); } } //System.Collections.Generic.IList<string > tmp = l.Values; for (i = 0; i < l2.Count; i++) { Response.Output.WriteLine(l2 [i]); } } finally { con.Close(); } }
public void AddColor(float x, float r, float g, float b, float a) { if (samples.ContainsKey(x)) { samples.Remove(x); } else { x_min = Math.Min(x_min, x); x_max = Math.Max(x_max, x); } samples.Add(x, new Vector4(r, g, b, a)); }
/// <summary> /// /// </summary> /// <param name="child"></param> public void AddChild(Node child) { if (child == null) { return; } if (child.NameType == nBrowser.NodeType.Browser || child.NameType == nBrowser.NodeType.Gateway) { Children.Add(child.Id, child); ChildrenKeys.Add(child.Id); } else if (child.NameType == NodeType.DefaultBrowser) { DefaultChildren.Add(child.Id, child); DefaultChildrenKeys.Add(child.Id); } }
protected override void OnLoad (EventArgs e) { base.OnLoad (e); MySqlConnection con = new MySqlConnection ("Server=127.0.0.1;Database=dht;Uid=dht;Pwd=sgv54hnf3ha142s3dfg4ad5sh;"); con.Open (); try { MySqlCommand cmd = new MySqlCommand ("SELECT MAX(id) AS max_id , MIN(id) AS min_id FROM nodes", con); IDataReader r; r = cmd.ExecuteReader (CommandBehavior.SingleRow); if (!r.Read ()) return; long max = r.GetInt64 (0); long min = r.GetInt64 (1); r.Close (); cmd.CommandText = "SELECT id, endpoint FROM nodes WHERE id >= @id and lastupdate>(subtime(CURRENT_TIMESTAMP,'05:00:00')) order by id LIMIT 0,1"; cmd.Parameters.Add ("@id", MySqlDbType.Int64); System.Random rnd = new System.Random (); System.Collections.Generic.SortedList<long,string > l = new System.Collections.Generic.SortedList<long, string> (); System.Collections.Generic.List<string > l2 = new System.Collections.Generic.List<string> (); int i; for (i=0; i<10; i++) { long id = getrand (rnd, min, max); //Response.Output.WriteLine (id); cmd.Parameters [0].Value = id; r = cmd.ExecuteReader (CommandBehavior.SingleRow); try { if (!r.Read ()) continue; try { l.Add (r.GetInt64 (0), r.GetString (1)); l2.Add (r.GetString (1)); } catch { } } finally { r.Close (); } } //System.Collections.Generic.IList<string > tmp = l.Values; for (i=0; i<l2.Count; i++) { Response.Output.WriteLine (l2 [i]); } } finally { con.Close (); } }
public void MapperPerformsMapOperation() { var filePath = "file1.txt"; var fileContent = "whatever am i"; storage.Store(filePath, fileContent); var mapper = new Mapper(filePath, (key, value) => { var result = new System.Collections.Generic.SortedList<string, string>(); foreach (var w in value.Split(' ')) result.Add(w, "1"); return result; }, this.storage); var mapResult = mapper.PerformMap(); mapResult.Count().ShouldBe(3); }
static StackObject *Add_2(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ILRuntime.Runtime.Intepreter.ILTypeInstance @value = (ILRuntime.Runtime.Intepreter.ILTypeInstance) typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Int32 @key = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 3); System.Collections.Generic.SortedList <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.SortedList <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance>) typeof(System.Collections.Generic.SortedList <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Add(@key, @value); return(__ret); }
public void Seed(int seed) { mSeed = seed; System.Random random = new System.Random(seed); System.Collections.Generic.SortedList <int, byte> list = new System.Collections.Generic.SortedList <int, byte>(256); byte u1 = 0; do { list.Add(random.Next(), u1); ++u1; } while (u1 != 0); // Copy into array. foreach (System.Collections.Generic.KeyValuePair <int, byte> pair in list) { perm[u1] = pair.Value; perm[u1 + 256] = pair.Value; ++u1; } }
private void btnLoadCRCList_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "*.txt|*.txt"; ofd.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; if (ofd.ShowDialog() == DialogResult.OK) { m_CRCList = new System.Collections.Generic.SortedList <uint, string>(); System.IO.StreamReader sr = System.IO.File.OpenText(ofd.FileName); string line; while ((line = sr.ReadLine()) != null) { string[] vals = line.Split(" ".ToCharArray()); m_CRCList.Add(uint.Parse(vals[0]), vals[1]); } sr.Close(); } }
private Node InitializeTree() { Node root = new Node(); //Custom Sorted List, to allow where Multple files in Diff directorys might have the same //filename. So still to some degree first come first serve but might be close enough //to how microsoft System to match much more closely. System.Collections.Generic.SortedList<string, System.Collections.Generic.List<nBrowser.File>> list; list = new System.Collections.Generic.SortedList<string, System.Collections.Generic.List<nBrowser.File>>(); for (int i = 0;i <= Browserfiles.Count - 1;i++) { if (list.ContainsKey(nbrowserfiles[i].FileName) == false) { System.Collections.Generic.List<nBrowser.File> l; l = new System.Collections.Generic.List<nBrowser.File>(); list.Add(nbrowserfiles[i].FileName, l); } list[nbrowserfiles[i].FileName].Add(nbrowserfiles[i]); } nBrowser.File[] files = new nBrowser.File[Browserfiles.Count]; int count = 0; for (int i = 0;i <= list.Count - 1;i++) { System.Collections.Generic.List<nBrowser.File> l = list[list.Keys[i]]; for (int b = 0;b <= l.Count - 1;b++) { files[count] = l[b]; count++; } } #region Connect Nodes for (int i = 0;i <= Browserfiles.Count - 1;i++) { for (int a = 0;a <= files[i].Keys.Length - 1;a++) { Node child = files[i].GetNode(files[i].Keys[a]); Node parent = null; if (child.ParentId.Length > 0) { parent = this.GetNode(child.ParentId); if (parent == null) throw new nBrowser.Exception(String.Format("Parent not found with id = {0}", child.ParentId)); } if (parent == null) parent = root; parent.AddChild(child); } } #endregion #region Inject DefaultBrowser Nodes for (int i = 0;i <= Browserfiles.Count - 1;i++) { for (int a = 0;a <= files[i].DefaultKeys.Length - 1;a++) { Node defaultNode = files[i].GetDefaultNode(files[i].DefaultKeys[a]); Node node = this.GetNode(defaultNode.Id); if (node == defaultNode) { // there is no regular node so the defaultNode is already at // the correct spot in the tree. continue; } Node parentNode = this.GetNode(node.ParentId); if (parentNode == null) parentNode = root; // insert the default node between the regular node and it's parent. parentNode.RemoveChild(node); defaultNode.AddChild(node); parentNode.AddChild(defaultNode); } } #endregion #region Merge Ref Nodes for (int i = 0;i <= Browserfiles.Count - 1;i++) { foreach (Node refNode in files[i].RefNodes) { GetNode(refNode.RefId).MergeFrom(refNode); } } #endregion return root; }
//public object this[double index] //{ // get // { // return List[index]; // } // set // { // List[index] = value; // } //} #endregion #region IList int System.Collections.IList.Add(object value) { List.Add(List.Count, value); return(List.Count); }
public void Seed(int seed) { mSeed = seed; System.Random random = new System.Random(seed); System.Collections.Generic.SortedList<int, byte> list = new System.Collections.Generic.SortedList<int, byte>(256); byte u1 = 0; do { list.Add(random.Next(), u1); ++u1; } while (u1 != 0); // Copy into array. foreach (System.Collections.Generic.KeyValuePair<int, byte> pair in list) { perm[u1] = pair.Value; perm[u1 + 256] = pair.Value; ++u1; } }
/// <summary> /// Find all non-abstract classes derived from the specified class. /// </summary> /// <param name="baseType"> /// The topmost class in the class hierarchy. /// </param> /// <returns> /// All non-abstract classes derived from the baseType with a default constructor. /// </returns> public static System.Collections.Generic.List <System.Type> GetDerivedClasses(System.Type baseType) { var result = new System.Collections.Generic.List <System.Type>(); // try // { // Loop through each loaded assembly and each exported type // looking for non-abstract types that derive from our property//s type foreach (var t in from a in System.AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where (!t.IsAbstract) && t.IsSubclassOf(baseType) where (t.GetConstructor(System.Type.EmptyTypes) != null) where result.IndexOf(t) == -1 select t) { result.Add(t); } // } // catch (System.Exception) // { // This exception should only happen in a Design environment in which the // controls that use this method are being changed and recompiled. // // This is because of a charming //feature// that Visual Studio has while // you stay in a single Visual Studio session. (If you exit and re-enter Visual Studio, // this problem goes away.) // When a project is compiled, its dll is placed in a temp directory and used // by web pages in the solution. When it is re-compiled, the new dll is placed in a // new temp directory, but the pre-existing usages of the control still point - by default - // to the old temp directory. // This has an unpleasant side effect (among many others!) of causing multiple versions of the // same class definition to appear in the list of loaded dll assemblies. This can cause // a duplication error. // } var sortedList = new System.Collections.Generic.SortedList <string, System.Type>(result.Capacity); foreach (var t in result) { // try // { sortedList.Add($"{t.Name}::{t.FullName}::{t.GUID}", t); // } // catch (System.Exception) // { // Ditto on the reason for an exception here. // } } var sortedResult = new System.Collections.Generic.List <System.Type> { Capacity = sortedList.Count }; for (var i = 0; i <= (sortedList.Count - 1); i++) { sortedResult.Add(result[result.IndexOf(sortedList.Values[i])]); } return(sortedResult); }
/// <summary> /// Parse the list stylesheet response. /// </summary> /// <param name="hDocument">The GeosoftXML response</param> /// <param name="oStylesheets">The list of stylesheets</param> public void ListStylesheets(System.Xml.XmlDocument hDocument, out System.Collections.Generic.SortedList<string, string> oStylesheets) { System.Xml.XmlNodeList hItemList; System.Xml.XmlNode hNode; oStylesheets = new System.Collections.Generic.SortedList<string,string>(); try { // --- find all the item elements located anywhere in the document --- hItemList = hDocument.SelectNodes("//" + Constant.Tag.STYLESHEET_TAG); if (hItemList == null) throw new DapException("No stylesheets found"); // --- loop through all the datasets adding them to the list --- for (int i = 0; i < hItemList.Count; i++) { System.Xml.XmlNode hAttr; string strName = string.Empty; string strEdition = string.Empty; hNode = hItemList[i]; hAttr = hNode.Attributes.GetNamedItem(Constant.Attribute.NAME_ATTR); if (hAttr != null && hAttr.Value != null) strName = hAttr.Value; hAttr = hNode.Attributes.GetNamedItem(Constant.Attribute.EDITION_ATTR); if (hAttr != null && hAttr.Value != null) strEdition = hAttr.Value; if (!string.IsNullOrEmpty(strName) && !oStylesheets.ContainsKey(strName)) oStylesheets.Add(strName, strEdition); } } catch (Exception e) { throw new DapException("Error compiling list of stylesheets", e); } }
/// <summary> /// Sort the index of SequenceAlignmentMap by RName then by Pos. /// Fill the index (sorted by RName then by Pos) into a list, when the list size reaches /// the maximum limit, write the list to file and clear the list. /// </summary> private SortedDictionary<string, IList<string>> SortByChromosomeCoordinates() { SortedDictionary<string, IList<string>> sortedFiles = new SortedDictionary<string, IList<string>>(); IList<string> files = null; var groups = new System.Collections.Generic.SortedList<string, System.Collections.Generic.SortedList<object, string>>(); System.Collections.Generic.SortedList<object, string> sortedList = null; for (int index = 0; index < sequenceAlignMap.QuerySequences.Count; index++) { SAMAlignedSequence alignedSeq = sequenceAlignMap.QuerySequences[index]; if (!groups.TryGetValue(alignedSeq.RName, out sortedList)) { sortedList = new System.Collections.Generic.SortedList<object, string>(); groups.Add(alignedSeq.RName, sortedList); } string indices = string.Empty; if (!sortedList.TryGetValue(alignedSeq.Pos, out indices)) { sortedList.Add(alignedSeq.Pos, index.ToString(CultureInfo.InvariantCulture)); } else { indices = string.Format(CultureInfo.InvariantCulture, "{0},{1}", indices, index.ToString(CultureInfo.InvariantCulture)); sortedList[alignedSeq.Pos] = indices; } if (sortedList.Count >= SortedListMaxCount) { if (!sortedFiles.TryGetValue(alignedSeq.RName, out files)) { files = new List<string>(); sortedFiles.Add(alignedSeq.RName, files); } files.Add(WriteToFile(sortedList)); sortedList.Clear(); } } foreach (KeyValuePair<string, System.Collections.Generic.SortedList<object, string>> group in groups) { if (group.Value.Count > 0) { if (!sortedFiles.TryGetValue(group.Key, out files)) { files = new List<string>(); sortedFiles.Add(group.Key, files); } files.Add(WriteToFile(group.Value)); group.Value.Clear(); } } return sortedFiles; }
static void Main(string[] args) { ArrayList <string> list = new ArrayList <string>() { "A", "B", "C", "D", "E", "F", "J", "H", "I", "G", "K", "L" }; // перебор значений foreach (object o in list) { Console.Write($"{o} "); } //количество элементов Console.WriteLine($"\nколичество элементов: {list.Count}"); Console.WriteLine($"\n - заносим в список элемент 'FF' "); list.Add("FF"); // заносим в список строковый массив // перебор значений foreach (object o in list) { Console.Write($"{o} "); } // удаляем первый элемент Console.WriteLine($"\n{list[0]} - удаляем первый элемент"); list.RemoveAt(0); // перебор значений for (int i = 0; i < list.Count; i++) { Console.Write($"{list[i]} "); } // получение элемента по индексу Console.WriteLine($"\n{list[0]} - получение элемента по индексу [0]"); //поиск в коллекции значения if (list.Contains("E")) { // перебор значений foreach (object o in list) { if (o == "E") { Console.Write($"\n{o} - 'E' поиск успешен"); } else { Console.Write($"\n{o} - не 'E' "); } } } Console.WriteLine($"\n"); var hs = new System.Collections.Generic.HashSet <long>(); for (long i = 0; i < 10; i++) { hs.Add(i); } foreach (var item in hs) { Console.Write($" {item}"); } Console.WriteLine(); for (int i = 0; i < hs.Count; i++) { hs.Remove(i + 1); } foreach (var item in hs) { Console.Write($" {item}"); } Console.WriteLine("\n"); var sl = new System.Collections.Generic.SortedList <long, string>(); foreach (var item in hs) { sl.Add(item, "Book"); } foreach (var item in sl) { Console.Write($" {item}"); } Console.WriteLine("\n"); foreach (var item in sl) { if (item.Key == 9) { Console.WriteLine($"Совпадение по запросу: 9 - найдено! ({item.Key})"); } else { Console.WriteLine($"Совпадение по запросу: 9 - не найдено!!! ({item.Key})"); } } Console.WriteLine("\n"); var CrocoSortedList = new System.Collections.Generic.SortedList <float, Crocodile <string> >(); CrocoSortedList.Add(0, new Crocodile <string>("Crocodile1", 4)); CrocoSortedList.Add(1, new Crocodile <string>("Crocodile2", 3)); CrocoSortedList.Add(2, new Crocodile <string>("Crocodile3", 2)); CrocoSortedList.Add(3, new Crocodile <string>("Crocodile4", 5)); CrocoSortedList.Add(4, new Crocodile <string>("Crocodile5", 7)); CrocoSortedList.Add(5, new Crocodile <string>("Crocodile6", 6)); CrocoSortedList.Add(6, new Crocodile <string>("Crocodile7", 9)); CrocoSortedList.Add(7, new Crocodile <string>("Crocodile8", 8)); CrocoSortedList.Add(8, new Crocodile <string>("Crocodile9", 2)); CrocoSortedList.Add(9, new Crocodile <string>("Crocodile10", 1)); // Вывод значения полей объектов на консоль. Используется перегруженный метод ToString() класса Crocodile<T> . foreach (object o in CrocoSortedList) { Console.Write($"\n{o} "); } Console.WriteLine("\n"); //поиск в коллекции значения foreach (var item in CrocoSortedList) { if (item.Value == CrocoSortedList[3]) { Console.WriteLine($"Совпадение по запросу: Crocodile4 - найдено! ({item.Key})"); } else { Console.WriteLine($"Совпадение по запросу: Crocodile4 - не найдено!!! ({item.Key})"); } } Console.WriteLine("\n"); var CrocoHashSet = new System.Collections.Generic.HashSet <Crocodile <string> >(); foreach (var item in CrocoSortedList) { CrocoHashSet.Add(item.Value); } // Вывод значения полей объектов на консоль. Используется перегруженный метод ToString() класса Crocodile<T> . foreach (object o in CrocoHashSet) { Console.Write($"\n{o} "); } Console.WriteLine("\n"); // Удаляем элемент с идентификационным номером 3. Компаратор будет сравнивать объекты именно по идентификационному номеру соответствие имени объекта не учитывается. Console.WriteLine("\nУдаляем элемент с идентификатором(\"3\")"); CrocoHashSet.Remove(new Crocodile <string>("Crocodile4", 5)); // Вывод значения полей объектов на консоль. Используется перегруженный метод ToString() класса Crocodile<T> . foreach (object o in CrocoHashSet) { Console.Write($"\n{o} "); } Console.WriteLine("\n"); //------------------------------------------------------------------------------------------------------- ObservableCollection <Crocodile <string> > crocodiles = new ObservableCollection <Crocodile <string> > { new Crocodile <string>("Crocodile4", 5), new Crocodile <string>("Crocodile11", 6), new Crocodile <string>("Crocodile12", 7) }; crocodiles.CollectionChanged += Users_CollectionChanged; crocodiles.Add(new Crocodile <string>("Crocodile13", 5)); crocodiles.RemoveAt(1); crocodiles[0] = new Crocodile <string>("Crocodile14", 6); foreach (Crocodile <string> crocodile in crocodiles) { Console.WriteLine(crocodile.Name); } Console.ReadLine(); }
/// <summary> /// 一个静态构造方法。 /// </summary> static VerifyCode() { var configSection = GetSection("VerifyCode"); if (configSection != null) { if (!string.IsNullOrEmpty(configSection["VerifyCodeEnumerable"])) { System.Collections.Generic.List <string> charVerifyCodeEnumerable = new System.Collections.Generic.List <string>(); //字符验证码枚举列表。 System.Collections.Generic.SortedList <string, string> keyValueVerifyCodeEnumerable = new System.Collections.Generic.SortedList <string, string>(); //键值对(问题和答案)验证码列表。 string[] keyValues = configSection["VerifyCodeEnumerable"].Split(','); foreach (var tmp in keyValues) { int eqIndex = tmp.IndexOf('='); if (eqIndex > 0) //如果是键值对验证码。 { string key = tmp.Substring(0, eqIndex); string value = tmp.Substring(eqIndex + 1); if (!keyValueVerifyCodeEnumerable.ContainsKey(key)) { keyValueVerifyCodeEnumerable.Add(key, value); } } else if (!charVerifyCodeEnumerable.Contains(tmp)) //如果是字符型验证码。 { charVerifyCodeEnumerable.Add(tmp); } } VerifyCode.VerifyCodeEnumerable = charVerifyCodeEnumerable.ToArray(); VerifyCode.KeyValueVerifyCodeEnumerable = keyValueVerifyCodeEnumerable; } if (!string.IsNullOrEmpty(configSection["Length"])) { VerifyCode.Length = System.Convert.ToInt32(configSection["Length"]); } if (!string.IsNullOrEmpty(configSection["BendingAngle"])) { VerifyCode.BendingAngle = System.Convert.ToInt32(configSection["BendingAngle"]); } if (!string.IsNullOrEmpty(configSection["FontSize"])) { VerifyCode.FontSize = System.Convert.ToInt32(configSection["FontSize"]); } if (!string.IsNullOrEmpty(configSection["Padding"])) { VerifyCode.Padding = System.Convert.ToInt32(configSection["Padding"]); } if (!string.IsNullOrEmpty(configSection["ForeColors"])) { System.Collections.Generic.List <System.Drawing.Color> cs = new System.Collections.Generic.List <System.Drawing.Color>(); string[] vs = configSection["ForeColors"].Split(','); foreach (var tmp in vs) { cs.Add(System.Drawing.ColorTranslator.FromHtml(tmp)); } VerifyCode.ForeColors = cs.ToArray(); } if (!string.IsNullOrEmpty(configSection["Fonts"])) { string[] vs = configSection["Fonts"].Split(','); VerifyCode.Fonts = vs; } } }
/// <summary> /// Adds an integer value to the collection. /// </summary> /// <param name="nValue">The integer value to add.</param> public void Add(int nValue) { _list.Add(nValue, null); }
static private System.Collections.Generic.SortedList <System.UInt64, System.IntPtr> ReadFile(System.IO.BinaryReader binaryReader, AddressLibrary.Header header) { var offsets = new System.Collections.Generic.SortedList <System.UInt64, System.IntPtr>(header.AddressCount); System.UInt64 identifier; System.UInt64 offset; System.UInt64 previousIdentifier = 0; System.UInt64 previousOffset = 0; for (var index = 0; index < header.AddressCount; index++) { var type = binaryReader.ReadByte(); var identifierType = type & 0xF; var offsetType = type >> 4; switch ((AddressLibrary.ReadTypes)identifierType) { case AddressLibrary.ReadTypes.ReadUInt64: { identifier = binaryReader.ReadUInt64(); break; } case AddressLibrary.ReadTypes.Add1: { identifier = previousIdentifier + 1; break; } case AddressLibrary.ReadTypes.AddReadByte: { identifier = previousIdentifier + binaryReader.ReadByte(); break; } case AddressLibrary.ReadTypes.SubtractReadByte: { identifier = previousIdentifier - binaryReader.ReadByte(); break; } case AddressLibrary.ReadTypes.AddReadUInt16: { identifier = previousIdentifier + binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.SubtractReadUInt16: { identifier = previousIdentifier - binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.ReadUInt16: { identifier = binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.ReadUInt32: { identifier = binaryReader.ReadUInt32(); break; } default: { try { throw new System.InvalidOperationException($"{nameof(AddressLibrary)}: Unexpected {nameof(identifierType)} encountered, {identifierType}."); } catch (System.InvalidOperationException invalidOperationException) { Log.Information($"{invalidOperationException}"); throw; } } } var temporaryOffset = (offsetType & 8) != 0 ? previousOffset / (System.UInt64)header.PointerSize : previousOffset; switch ((AddressLibrary.ReadTypes)(offsetType & 7)) { case AddressLibrary.ReadTypes.ReadUInt64: { offset = binaryReader.ReadUInt64(); break; } case AddressLibrary.ReadTypes.Add1: { offset = temporaryOffset + 1; break; } case AddressLibrary.ReadTypes.AddReadByte: { offset = temporaryOffset + binaryReader.ReadByte(); break; } case AddressLibrary.ReadTypes.SubtractReadByte: { offset = temporaryOffset - binaryReader.ReadByte(); break; } case AddressLibrary.ReadTypes.AddReadUInt16: { offset = temporaryOffset + binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.SubtractReadUInt16: { offset = temporaryOffset - binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.ReadUInt16: { offset = binaryReader.ReadUInt16(); break; } case AddressLibrary.ReadTypes.ReadUInt32: { offset = binaryReader.ReadUInt32(); break; } default: { try { throw new System.InvalidOperationException($"{nameof(AddressLibrary)}: Unexpected {nameof(offsetType)} encountered, {offsetType}."); } catch (System.InvalidOperationException invalidOperationException) { Log.Information($"{invalidOperationException}"); throw; } } } if ((offsetType & 8) != 0) { offset *= (System.UInt64)header.PointerSize; } offsets.Add(identifier, new System.IntPtr((System.Int64)offset)); previousIdentifier = identifier; previousOffset = offset; } return(offsets); }
private Node InitializeTree() { Node root = new Node(); //Custom Sorted List, to allow where Multple files in Diff directorys might have the same //filename. So still to some degree first come first serve but might be close enough //to how microsoft System to match much more closely. System.Collections.Generic.SortedList <string, System.Collections.Generic.List <nBrowser.File> > list; list = new System.Collections.Generic.SortedList <string, System.Collections.Generic.List <nBrowser.File> >(); for (int i = 0; i <= Browserfiles.Count - 1; i++) { if (list.ContainsKey(nbrowserfiles[i].FileName) == false) { System.Collections.Generic.List <nBrowser.File> l; l = new System.Collections.Generic.List <nBrowser.File>(); list.Add(nbrowserfiles[i].FileName, l); } list[nbrowserfiles[i].FileName].Add(nbrowserfiles[i]); } nBrowser.File[] files = new nBrowser.File[Browserfiles.Count]; int count = 0; for (int i = 0; i <= list.Count - 1; i++) { System.Collections.Generic.List <nBrowser.File> l = list[list.Keys[i]]; for (int b = 0; b <= l.Count - 1; b++) { files[count] = l[b]; count++; } } #region Connect Nodes for (int i = 0; i <= Browserfiles.Count - 1; i++) { for (int a = 0; a <= files[i].Keys.Length - 1; a++) { Node child = files[i].GetNode(files[i].Keys[a]); Node parent = null; if (child.ParentId.Length > 0) { parent = this.GetNode(child.ParentId); if (parent == null) { throw new nBrowser.Exception(String.Format("Parent not found with id = {0}", child.ParentId)); } } if (parent == null) { parent = root; } parent.AddChild(child); } } #endregion #region Inject DefaultBrowser Nodes for (int i = 0; i <= Browserfiles.Count - 1; i++) { for (int a = 0; a <= files[i].DefaultKeys.Length - 1; a++) { Node defaultNode = files[i].GetDefaultNode(files[i].DefaultKeys[a]); Node node = this.GetNode(defaultNode.Id); if (node == defaultNode) { // there is no regular node so the defaultNode is already at // the correct spot in the tree. continue; } Node parentNode = this.GetNode(node.ParentId); if (parentNode == null) { parentNode = root; } // insert the default node between the regular node and it's parent. parentNode.RemoveChild(node); defaultNode.AddChild(node); parentNode.AddChild(defaultNode); } } #endregion #region Merge Ref Nodes for (int i = 0; i <= Browserfiles.Count - 1; i++) { foreach (Node refNode in files[i].RefNodes) { GetNode(refNode.RefId).MergeFrom(refNode); } } #endregion return(root); }