/// <summary> /// This method sorts the items in a listbox. /// </summary> /// <param name="items">The list control.</param> /// <param name="Descending">Whether to sort the list box descending. </param> public static void SortListItems(this ListItemCollection items, bool Descending) { System.Collections.Generic.List<ListItem> list = new System.Collections.Generic.List<ListItem>(); foreach (ListItem i in items) { list.Add(i); } if (Descending) { IEnumerable<ListItem> itemEnum = from item in list orderby item.Text descending select item; items.Clear(); items.AddRange(itemEnum.ToArray()); // anonymous delegate list.Sort(delegate(ListItem x, ListItem y) { return y.Text.CompareTo(x.Text); }); } else { IEnumerable<ListItem> itemEnum = from item in list orderby item.Text ascending select item; items.Clear(); items.AddRange(itemEnum.ToArray()); //list.Sort(delegate(ListItem x, ListItem y) { return x.Text.CompareTo(y.Text); }); } }
/// <summary> /// Reorders package operations so that operations occur in the same order as index with additional /// handling of satellite packages so that are always processed relative to the corresponding core package. /// </summary> private static IList<PackageOperation> Reorder(this List<IndexedPackageOperation> operations) { operations.Sort((a, b) => a.Index - b.Index); var satellitePackageOperations = new List<IndexedPackageOperation>(); for (int i = 0; i < operations.Count; i++) { var operation = operations[i]; if (operation.Operation.Package.IsSatellitePackage()) { satellitePackageOperations.Add(operation); operations.RemoveAt(i); i--; } } if (satellitePackageOperations.Count > 0) { // For satellite packages, we need to ensure that the package is uninstalled prior to uninstalling the core package. This is because the satellite package has to remove // satellite files from the lib directory so that the core package does not leave any files left over. The reverse is true for install operations. As a trivial fix, we are // going to trivially move all uninstall satellite operations to the beginning of our reduced list and all install operations at the end. operations.InsertRange(0, satellitePackageOperations.Where(s => s.Operation.Action == PackageAction.Uninstall)); operations.AddRange(satellitePackageOperations.Where(s => s.Operation.Action == PackageAction.Install)); } return operations.Select(o => o.Operation) .ToList(); }
private static void AddProjectsRecursive(this List<EnvDTE.Project> list, EnvDTE.Project subProject) { if (subProject.Kind == ProjectKinds.vsProjectKindSolutionFolder) list.AddRange(GetSolutionFolderProjects(subProject)); else list.Add(subProject); }
public static void MergeIdenticalItems(this List<ChromosomeCountSlimItem> chroms) { Console.WriteLine("All groups = {0}", chroms.Count); var uniqueQueryGroups = (from g in chroms.GroupBy(l => l.Queries.Count) select g.ToArray()).ToArray(); Console.WriteLine("Groups with same unique queries = {0}", uniqueQueryGroups.Length); chroms.Clear(); foreach (var uqg in uniqueQueryGroups) { var queryCountGroups = (from g in uqg.GroupBy(l => l.GetQueryCount()) select g.ToArray()).ToArray(); foreach (var qcg in queryCountGroups) { var qnameGroups = (from g in qcg.GroupBy(g => g.Queries[0].Qname) select g.ToList()).ToArray(); foreach (var qg in qnameGroups) { if (qg.Count > 1) { DoMergeIdentical(qg); } chroms.AddRange(qg); } qnameGroups = null; } queryCountGroups = null; } uniqueQueryGroups = null; }
public static RVList<LNode> WithSpliced(this RVList<LNode> list, LNode node, Symbol listName) { if (node.Calls(listName)) return list.AddRange(node.Args); else return list.Add(node); }
public static void SpliceAdd(this RWList<LNode> list, LNode node, Symbol listName) { if (node.Calls(listName)) list.AddRange(node.Args); else list.Add(node); }
public static void FromString(this ComboBox.ObjectCollection coll, string values) { if (!string.IsNullOrWhiteSpace(values)) { string[] items = values.Split(new[] { _delimiter }, StringSplitOptions.RemoveEmptyEntries); coll.AddRange(items); } }
public static void ConnectTagsToArticle(this DbSet<ArticleTag> source, Article article, IQueryable<Tag> tags) { var articleTags = tags.Select(t => new ArticleTag { ArticleId = article.ArticleId, TagId = t.TagId, }).ToList(); source.AddRange(articleTags); }
public static void AddIfMissing(this List<string> collection, params string[] tags) { if (collection == null) throw new NullReferenceException("string collection is null, unable to Add()"); if (tags == null || tags.Length == 0) return; collection.AddRange(tags.Except(collection).ToArray()); }
public static void AddRange(this MediaTypeFormatterCollection collection, IEnumerable<MediaTypeFormatter> items) { if (collection == null) { throw Error.ArgumentNull("collection"); } collection.AddRange(items); }
public static void Deserialize(this List<FileMail> list, string fileName) { var serializer = new XmlSerializer(typeof(List<FileMail>)); using (var stream = File.OpenRead(fileName)) { var other = (List<FileMail>)(serializer.Deserialize(stream)); list.Clear(); list.AddRange(other); } }
/* * Removes from the ArrayList those elements that exist in a given ArrayList */ public static void Exclusive(this ArrayList arrayList, ArrayList sourceArrayList){ ArrayList exclusives = new ArrayList(); foreach (object anObject in arrayList){ if (!sourceArrayList.Contains(anObject)){ exclusives.Add (anObject); } } arrayList.RemoveRange(0, arrayList.Count); arrayList.AddRange(exclusives); }
private static void AddTopLevelOrNestedProjects(this List<EnvDTE.Project> list, EnvDTE.Project project) { if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder) { list.AddRange(GetSolutionFolderProjects(project)); } else { list.Add(project); } }
/// <summary> /// Merge <paramref name="source"/> into the current instance, /// using target property as the key. /// </summary> /// <param name="list">The <see cref="MappedFieldList"/> that acts as the this instance.</param> /// <param name="source">The list to merge into the current instance.</param> /// <remarks> /// When both the current instance and <paramref name="source"/> contain a mapping /// for the same target, the mapping from <paramref name="source"/> will take precedence. /// </remarks> public static void MergeOnTarget(this MappedFieldList list, MappedFieldList source) { foreach (var item in source) { if (list.ContainsTarget(item.Target)) { list.RemoveByTarget(item.Target); } } list.AddRange(source); }
public static List<IRating> ExtractFromUsers(this List<IRating> ratings, IEnumerable<IUser> users, bool copyRatings = true) { if (users == null) return null; ratings.Clear(); foreach (var user in users) ratings.AddRange(copyRatings ? user.Ratings.Select(rating => rating.Clone()) : user.Ratings); return ratings; }
public static void AddAsFirstControl(this Control.ControlCollection controlCollection, Control newControl) { var controls = new Control[controlCollection.Count]; for (var i = 0; i < controlCollection.Count; i++) { controls[i] = controlCollection[i]; } controlCollection.Clear(); controlCollection.Add(newControl); controlCollection.AddRange(controls); for (int i = 0; i < controlCollection.Count; i++) { controlCollection[i].TabIndex = controlCollection.Count - i - 1; } }
/// <summary> /// Creates all tags in supplied collection that don't already exist and returns the newly created tags. /// </summary> public static IEnumerable<Tag> CreateAllIfNotExists(this DbSet<Tag> source, IEnumerable<string> tags) { var tagSet = new HashSet<string>(tags); var existingTags = source .Where(t => tagSet.Contains(t.Name)) .Select(t => t.Name) .ToList(); // consume to get result out of DB tagSet.RemoveWhere(tag => existingTags.Contains(tag)); var newTags = tagSet.Select(t => new Tag { Name = t }); source.AddRange(newTags); return newTags; }
/// <summary> /// Adds listeners to Trace that pass output into the given msbuild logger, making Trace /// calls visible in build output. VersionTools, for example, uses Trace. Returns the /// listeners to pass to RemoveMsBuildTraceListeners when the code using Trace is complete. /// </summary> public static MsBuildTraceListener[] AddMsBuildTraceListeners( this TraceListenerCollection listenerCollection, TaskLoggingHelper log) { var newListeners = new[] { TraceEventType.Error, TraceEventType.Warning, TraceEventType.Critical, TraceEventType.Information, TraceEventType.Verbose }.Select(t => new MsBuildTraceListener(log, t)).ToArray(); listenerCollection.AddRange(newListeners); return newListeners; }
/// <summary> /// Adds the columns. /// </summary> /// <param name="columns">The columns.</param> /// <param name="itemType">Type of the item.</param> /// <param name="owner">The owner.</param> /// <param name="prefix">The prefix.</param> /// <param name="tableName">Name of the table.</param> /// <param name="forFilter">if set to <c>true</c> [for filter].</param> /// <param name="displayColumns">The display columns.</param> /// <param name="columnOrder">The column order.</param> public static void AddColumns( this ColumnCollection columns, Type itemType, IRefreashable owner, string prefix = null, string tableName = null, bool forFilter = false, string[] displayColumns = null, IList<string> columnOrder = null) { //aggregate own and parent's columns and return in default order var columnsList = new ColumnCollection(); AddColumnsInternal(columnsList, itemType, owner, prefix, tableName, forFilter, displayColumns, columnOrder); columns.AddRange(columnsList.OrderBy(c => c.DefaultOrder)); }
/// <summary> /// Takes the dynamic object and creates the Sql Parameters from its properties /// </summary> /// <param name="oracleParameters"></param> /// <param name="otherParameters"></param> public static void CreateOracleParametersFromDynamic(this List<OracleParameter> oracleParameters, dynamic otherParameters) { var otherParametersObj = otherParameters as Object; if (otherParametersObj != null) { var oracleParams = otherParametersObj.GetType().GetProperties().Select( param => { object value = param.GetValue(otherParameters); if (param.Name.GetType().Name.ToLower() == "string" && value != null) { value = SafeSqlLiteral(value.ToString()); } return new OracleParameter("@" + Clean(param.Name), value); }).ToList(); oracleParameters.AddRange(oracleParams); } }
/// <summary> /// Same as AddRange(), but can filter out any duplicates. Filtering can be case insensitive, and ignore ending CR/LF's. /// </summary> /// <param name="uniqueOnly">Only add new items to the list.</param> /// <param name="ignoreCase">Case insensitive comparison flag.</param> /// <param name="ignoreCrLf">If the strings match, except for an ending CR/LF, return true.</param> /// <returns></returns> public static void AddRange(this List<string> thisItems, IEnumerable<string> collection, bool uniqueOnly, bool ignoreCase = true, bool ignoreCrLf = true) { if (collection == null) return; if (!uniqueOnly && !ignoreCrLf && !ignoreCase) { thisItems.AddRange(collection); return; } foreach (string item in collection) { thisItems.Add(item, uniqueOnly, ignoreCrLf, ignoreCase); } return; }
public static void Shrink(this List<Node> nodes) { nodes.Sort(); var old = nodes .Where(node=> node.Action != GameAction.Check) .OrderBy(node => Math.Abs(0.5 - node.Odds)) .ToList(); var buffer = new List<Node>(nodes.Capacity); while (old.Count > 0) { var candidate = old[0]; old.RemoveAt(0); // get these out. if (candidate.Round == 0) { continue; } var match = old .Where(item => candidate.ByteOdds == item.ByteOdds && candidate.SubRound == item.SubRound && candidate.HasAmountToCall == item.HasAmountToCall && candidate.Action.ActionType == item.Action.ActionType) .OrderByDescending(item => Matcher.Node(candidate, item)).FirstOrDefault(); var m = match == null ? -1 : Matcher.Node(candidate, match); if (m > 0) { var merged = Node.Merge(candidate, match); buffer.Add(merged); old.Remove(match); } else { buffer.Add(candidate); } } nodes.Clear(); nodes.AddRange(buffer); nodes.Sort(); }
public static List<bool> Condition(this List<bool> table, bool test, string tableValues) { if (table.Count == 0) table.AddRange(tableValues.ToCharArray().Select(i => true)); if (table.Count != tableValues.Length) throw new Exception(); bool result = test; List<bool> res = new List<bool>(); for (int i = 0; i < tableValues.Length; i++) { switch (tableValues[i]) { // no modifier case '-': res.Add(table[i]); break; // if test is true case 'T': res.Add(table[i] && result); break; // if test is false case 'F': res.Add(table[i] && !result); break; default: res.Add(false); break; } } return res; }
public static void SpliceAdd(this WList<LNode> list, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) list.AddRange(node.Args); else list.Add(node); }
//--- Extension Methods --- /// <summary> /// Add a header to a web request. /// </summary> /// <param name="request">Target web request.</param> /// <param name="key">Header Key.</param> /// <param name="value">Header Value.</param> public static void AddHeader(this HttpWebRequest request, string key, string value) { if(string.Compare(key, DreamHeaders.ACCEPT, StringComparison.OrdinalIgnoreCase) == 0) { request.Accept = value; } else if(string.Compare(key, DreamHeaders.CONNECTION, StringComparison.OrdinalIgnoreCase) == 0) { // ignored: set automatically //request.Connection = value; } else if(string.Compare(key, DreamHeaders.CONTENT_LENGTH, StringComparison.OrdinalIgnoreCase) == 0) { request.ContentLength = long.Parse(value); } else if(string.Compare(key, DreamHeaders.CONTENT_TYPE, StringComparison.OrdinalIgnoreCase) == 0) { request.ContentType = value; } else if(string.Compare(key, DreamHeaders.EXPECT, StringComparison.OrdinalIgnoreCase) == 0) { // ignored: set automatically // request.Expect = value; } else if(string.Compare(key, DreamHeaders.DATE, StringComparison.OrdinalIgnoreCase) == 0) { // ignored: set automatically } else if(string.Compare(key, DreamHeaders.HOST, StringComparison.OrdinalIgnoreCase) == 0) { // ignored: set automatically } else if(string.Compare(key, DreamHeaders.IF_MODIFIED_SINCE, StringComparison.OrdinalIgnoreCase) == 0) { request.IfModifiedSince = DateTimeUtil.ParseInvariant(value); } else if(string.Compare(key, DreamHeaders.RANGE, StringComparison.OrdinalIgnoreCase) == 0) { // read range-specifier, with range (e.g. "bytes=500-999") var m = _rangeRegex.Match(value); if(m.Success) { var from = int.Parse(m.Groups["from"].Value); var to = m.Groups["to"].Success ? int.Parse(m.Groups["to"].Value) : -1; var rangeSpecifier = m.Groups["rangeSpecifier"].Success ? m.Groups["rangeSpecifier"].Value : null; if((rangeSpecifier != null) && (to >= 0)) { request.AddRange(rangeSpecifier, from, to); } else if(rangeSpecifier != null) { request.AddRange(rangeSpecifier, from); } else if(to >= 0) { request.AddRange(from, to); } else { request.AddRange(from); } } } else if(string.Compare(key, DreamHeaders.REFERER, StringComparison.OrdinalIgnoreCase) == 0) { request.Referer = value; } else if(string.Compare(key, DreamHeaders.PROXY_CONNECTION, StringComparison.OrdinalIgnoreCase) == 0) { // TODO (steveb): not implemented #if DEBUG throw new NotImplementedException("missing code"); #endif } else if(string.Compare(key, DreamHeaders.TRANSFER_ENCODING, StringComparison.OrdinalIgnoreCase) == 0) { // TODO (steveb): not implemented #if DEBUG throw new NotImplementedException("missing code"); #endif } else if(string.Compare(key, DreamHeaders.USER_AGENT, StringComparison.OrdinalIgnoreCase) == 0) { request.UserAgent = value; } else if(string.Compare(key, DreamHeaders.ETAG, StringComparison.OrdinalIgnoreCase) == 0) { // special case: ETAG needs to be a quoted string, so quote if it doesn't look quoted already if(value.StartsWithInvariant("\"") || value.StartsWithInvariant("'")) { request.Headers.Add(key, value); } else { request.Headers.Add(key, "\"" + value + "\""); } } else { request.Headers.Add(key, value); } }
public static VList<LNode> WithSpliced(this VList<LNode> list, LNode node, Symbol listName = null) { if (node.Calls(listName ?? CodeSymbols.Splice)) return list.AddRange(node.Args); else return list.Add(node); }
//--- Extension Methods --- /// <summary> /// Add a header to a web request. /// </summary> /// <param name="request">Target web request.</param> /// <param name="key">Header Key.</param> /// <param name="value">Header Value.</param> public static void AddHeader(this HttpWebRequest request, string key, string value) { if(string.Compare(key, DreamHeaders.ACCEPT, true) == 0) { request.Accept = value; } else if(string.Compare(key, DreamHeaders.CONNECTION, true) == 0) { // ignored: set automatically //request.Connection = value; } else if(string.Compare(key, DreamHeaders.CONTENT_LENGTH, true) == 0) { request.ContentLength = long.Parse(value); } else if(string.Compare(key, DreamHeaders.CONTENT_TYPE, true) == 0) { request.ContentType = value; } else if(string.Compare(key, DreamHeaders.EXPECT, true) == 0) { // ignored: set automatically // request.Expect = value; } else if(string.Compare(key, DreamHeaders.DATE, true) == 0) { // ignored: set automatically } else if(string.Compare(key, DreamHeaders.HOST, true) == 0) { // ignored: set automatically } else if(string.Compare(key, DreamHeaders.IF_MODIFIED_SINCE, true) == 0) { request.IfModifiedSince = DateTimeUtil.ParseInvariant(value); } else if(string.Compare(key, DreamHeaders.RANGE, true) == 0) { // read range-specifier, with range (e.g. "bytes=500-999") Match m = _rangeRegex.Match(value); if(m.Success) { int from = int.Parse(m.Groups["from"].Value); int to = m.Groups["to"].Success ? int.Parse(m.Groups["to"].Value) : -1; string rangeSpecifier = m.Groups["rangeSpecifier"].Success ? m.Groups["rangeSpecifier"].Value : null; if((rangeSpecifier != null) && (to >= 0)) { request.AddRange(rangeSpecifier, from, to); } else if(rangeSpecifier != null) { request.AddRange(rangeSpecifier, from); } else if(to >= 0) { request.AddRange(from, to); } else { request.AddRange(from); } } } else if(string.Compare(key, DreamHeaders.REFERER, true) == 0) { request.Referer = value; } else if(string.Compare(key, DreamHeaders.PROXY_CONNECTION, true) == 0) { // TODO (steveb): not implemented #if DEBUG throw new NotImplementedException("missing code"); #endif } else if(string.Compare(key, DreamHeaders.TRANSFER_ENCODING, true) == 0) { // TODO (steveb): not implemented #if DEBUG throw new NotImplementedException("missing code"); #endif } else if(string.Compare(key, DreamHeaders.USER_AGENT, true) == 0) { request.UserAgent = value; } else { request.Headers.Add(key, value); } }
private static void Update(this List<CdrRtdRecord> taRecordList, NearestPciCellRepository neighborRepository, MrRecordSet recordSet) { recordSet.ImportRecordSet(neighborRepository); taRecordList.AddRange(recordSet.RecordList.Select(x => new CdrRtdRecord(x))); }
internal static void SetHttpHeaders(this HttpWebRequest request, PhpArray array) { string headerName, headerValue; foreach (var arrayItem in array) { string headerItem = PhpVariable.AsString(arrayItem.Value); if (ParseHeader(headerItem, out headerName, out headerValue)) { Debug.Assert(headerName != null); Debug.Assert(headerValue != null); headerValue = headerValue.Trim(); //Accept Set by the Accept property. //Connection Set by the Connection property and KeepAlive property. //Content-Length Set by the ContentLength property. //Content-Type Set by the ContentType property. //Expect Set by the Expect property. //Date Set by the Date property. //Host Set by the Host property. //If-Modified-Since Set by the IfModifiedSince property. //Range Set by the AddRange method. //Referer Set by the Referer property. //Transfer-Encoding Set by the TransferEncoding property (the SendChunked property must be true). //User-Agent Set by the UserAgent property. switch (headerName.ToLowerInvariant()) { case "accept": request.Accept = headerValue; break; case "connection": if (headerValue.Equals("close", StringComparison.InvariantCultureIgnoreCase)) request.KeepAlive = false; else request.Connection = headerValue; break; case "content-length": request.ContentLength = System.Convert.ToInt32(headerValue); break; case "content-type": request.ContentType = headerValue; break; case "expect": if (headerValue.Equals("100-continue", StringComparison.InvariantCultureIgnoreCase)) request.ServicePoint.Expect100Continue = true; else request.Expect = headerValue; break; case "date": request.Date = System.Convert.ToDateTime(headerValue); break; case "host": request.Host = headerValue; break; case "if-modified-since": request.IfModifiedSince = System.Convert.ToDateTime(headerValue); break; case "range": request.AddRange(System.Convert.ToInt32(headerValue)); break; case "referer": request.Referer = headerValue; break; case "transfer-encoding": request.TransferEncoding = headerValue; break; case "user-agent": request.UserAgent = headerValue; break; default: request.Headers.Add(headerName, headerValue); break; } } } }
private static void Collect(this List<byte> l, ICryptoTransform transform, Stream input, int count) { byte[] buffer = new byte[count]; int numRead = input.Read(buffer, 0, count); Assert.Equal(count, numRead); byte[] buffer2 = new byte[count]; int numBytesWritten = transform.TransformBlock(buffer, 0, count, buffer2, 0); Array.Resize(ref buffer2, numBytesWritten); l.AddRange(buffer2); }