public List <Suggestion> GetSuggestionUsers(string keyword, int count) { try { if (string.IsNullOrEmpty(keyword)) { return(new List <Suggestion>()); } string displayMatch = "%" + keyword + "%"; int totalRecords = 0; int totalRecords2 = 0; System.Collections.ArrayList matchedUsers = UserController.GetUsersByDisplayName(PortalSettings.PortalId, displayMatch, 0, count, ref totalRecords, false, false); matchedUsers.AddRange(UserController.GetUsersByUserName(PortalSettings.PortalId, displayMatch, 0, count, ref totalRecords2, false, false)); IEnumerable <Suggestion> finalUsers = matchedUsers .Cast <UserInfo>() .Where(x => x.Membership.Approved) .Select(u => new Suggestion() { Value = u.UserID, Label = $"{u.DisplayName}" }); return(finalUsers.ToList().GroupBy(x => x.Value).Select(group => group.First()).ToList()); } catch (Exception) { return(new List <Suggestion>()); } }
private void btnCast_Click(object sender, EventArgs e) { listBox1.Items.Clear(); System.Collections.ArrayList TestCast = new System.Collections.ArrayList(); TestCast.Add("Test1"); TestCast.Add("Test2"); TestCast.Add("Test3"); IEnumerable<string> query = TestCast.Cast<string>().OrderBy(n => n).Select(n => n); foreach (var n in query) { listBox1.Items.Add("Cast : " + n); } int[] numbers = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var textNums = from n in numbers select strings[n]; foreach (var n in textNums) { listBox1.Items.Add("Select : " + n); } }
/// ----------------------------------------------------------------------------- /// <summary> /// Gets all the Searchable Module MetaData SearchDocuments within the timeframe for all portals /// </summary> /// ----------------------------------------------------------------------------- private int GetAndStoreModuleMetaData(ModuleIndexer indexer) { IEnumerable <SearchDocument> searchDocs; System.Collections.ArrayList portals = PortalController.Instance.GetPortals(); DateTime indexSince; int indexedCount = 0; //DateTime startDate foreach (PortalInfo portal in portals.Cast <PortalInfo>()) { indexSince = FixedIndexingStartDate(portal.PortalID); searchDocs = indexer.GetModuleMetaData(portal.PortalID, indexSince); StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } // Include Host Level Items indexSince = FixedIndexingStartDate(Null.NullInteger); searchDocs = indexer.GetModuleMetaData(Null.NullInteger, indexSince); StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); return(indexedCount); }
public ActionResult Get([FromHeader] string InstanceCollection) { System.Collections.ArrayList InsCol = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ArrayList>(InstanceCollection); List <InstanceContent> ContentListFromDB = (List <InstanceContent>)Contents.EntityCollection.Take(100000).OrderBy(c => c.Instance.Name).ToList(); List <string> Filter = InsCol.Cast <string>().ToList(); List <InstanceContent> ContentList = (from CL in ContentListFromDB.AsEnumerable() where Filter.Any(xx => xx.Contains(CL.Instance.Name)) select CL).ToList(); GalaxyObjects GObjcts = new GalaxyObjects(); GObjcts.List = ContentList; XmlSerializer x = new XmlSerializer(GObjcts.List.GetType()); XmlDocument doc = new XmlDocument(); System.IO.StringWriter sww = new System.IO.StringWriter(); XmlWriter writer = XmlWriter.Create(sww); x.Serialize(writer, GObjcts.List); return(new ContentResult { Content = sww.ToString(), ContentType = "application/xml" }); }
static void Main(string[] args) { /* string sentence = "the quick brown fox jumps over the lazy dog"; * // Split the string into individual words to create a collection. * string[] words = sentence.Split(' '); * * // Using query expression syntax. * var query = from word in words * group word.ToUpper() by word.Length into gr * orderby gr.Key * select new { Length = gr.Key, Words = gr }; * Console.WriteLine(query); * // Using method-based query syntax. * var query2 = words. * GroupBy(w => w.Length, w => w.ToUpper()). * Select(g => new { Length = g.Key, Words = g }). * OrderBy(o => o.Length); * * foreach (var obj in query) * { * Console.WriteLine("Words of length {0}:", obj.Length); * foreach (string word in obj.Words) * Console.WriteLine(word); * * } * Console.ReadKey();*/ System.Collections.ArrayList fruits = new System.Collections.ArrayList(); fruits.Add("mango"); fruits.Add("apple"); fruits.Add("lemon"); IEnumerable <string> query = fruits.Cast <string>().OrderBy(fruit => fruit).Select(fruit => fruit); // The following code, without the cast, doesn't compile. //IEnumerable<string> query1 = // fruits.OrderBy(fruit => fruit).Select(fruit => fruit); //IEnumerable<int> sequence = Enumerable.Range(0, 10); //var doubles = from int item in sequence // select (double)item; //foreach (double fr in doubles) //{ // Console.Write(fr); //} foreach (string fr in fruits) { Console.WriteLine(fr); } Console.ReadKey(); }
//在非类型化的集合上使用linq查询 需要cast private static void Cast() { var lists = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); var quary = from r in lists.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in quary) { Console.WriteLine("{0:A}", racer); } }
/// <summary> /// Populates breadcrumb /// </summary> /// <param name="contentId"></param> void PopulateBreadCrumb() { long contentId = 0; if (_contentId.Text != "") { contentId = Convert.ToInt64(_contentId.Text); } else { contentId = _parentContentId; } _rptBreadCrumb.DataSource = null; if (contentId > 0 && _contentList != null) { var list = from c in _contentList.ToList() where c.contentId.Equals(contentId) select c; if (list != null) { awContent cont = list.FirstOrDefault(); string lineage = cont.lineage.Trim(); System.Collections.ArrayList ids = new System.Collections.ArrayList(); if (!String.IsNullOrEmpty(lineage)) { string[] parentIds = lineage.Split('|'); for (int i = 0; i < parentIds.Length; i++) { if (!String.IsNullOrEmpty(parentIds[i])) { ids.Add(Convert.ToInt64(parentIds[i])); } } } //ids.Add(cont.contentId); var parentContents = from c in _contentList.ToList() where ids.Cast <long>().Contains(c.contentId) select c; _rptBreadCrumb.DataSource = parentContents; } } _rptBreadCrumb.DataBind(); _lblBreadCrumbCurrentContent.Text = _alias.Text; }
private static void Untyped() // Преобразование в строготипизированный запрос { var list = new System.Collections.ArrayList(Formula1.Champions as System.Collections.ICollection); var query = from r in list.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine("{0:A}", racer); } }
public static void ConvertWithCast() { var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); var query = from r in list.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine($"{racer:A}"); } }
static void Untyped() { var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); var query = from r in list.Cast<Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine("{0:A}", racer); } }
private void button30_Click(object sender, EventArgs e) { System.Collections.ArrayList arrList = new System.Collections.ArrayList(); arrList.Add(new Point(100, 100)); arrList.Add(new Point(100, 100)); //((Point) arrList[0]).X var q = from p in arrList.Cast<Point>() select p; this.dataGridView1.DataSource = q.ToList(); }
// Cast 转换对象类型 static void Untyped() { var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); // cast 将只能以 [index] 访问的集合转换成 .propertyName 的形式, 这样才可以用 foreach 遍历 var query = from r in list.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine("{0:A}", racer); } }
public static void ConvertWithCast() { Console.WriteLine("Convert elements of a non-generic collections using Cast<T>"); if (Formula1.GetChampions() is System.Collections.ICollection coll) { var list = new System.Collections.ArrayList(coll); var query = from r in list.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine($"{racer:A}"); } } }
private void Loaded(Object ss, EventArgs ee) { try { textBox3.Text = (string)ion2.settings.Get("accid"); textBox4.Text = (string)ion2.settings.Get("authsecret"); voiceMsgTxt.Text = (string)ion2.settings.Get("tts"); checkBox1.Checked = (bool)ion2.settings.Get("autoStartJob"); checkBox2.Checked = (bool)ion2.settings.Get("recordAudio"); offenderNumberTxt.Text = (string)ion2.settings.Get("faceNumber"); System.Collections.ArrayList ar = (System.Collections.ArrayList)ion2.settings.Get("tNum"); foreach (string at in ar.Cast <string>()) { outboundNumbers.Items.Add(at); } } catch (Exception ec) { Console.WriteLine(ec.Message); } }
public void Cast() { System.Collections.ArrayList fruits = new System.Collections.ArrayList(); fruits.Add("mango"); fruits.Add("apple"); fruits.Add("lemon"); IEnumerable <string> query = fruits.Cast <string>().OrderBy(fruit => fruit).Select(fruit => fruit); // The following code, without the cast, doesn't compile. //IEnumerable<string> query1 = // fruits.OrderBy(fruit => fruit).Select(fruit => fruit); foreach (string fruit in query) { Console.WriteLine(fruit); } }
/// ----------------------------------------------------------------------------- /// <summary> /// Gets all the Search Documents for the given timeframe. /// </summary> /// <param name="indexer"></param> /// ----------------------------------------------------------------------------- private int GetAndStoreSearchDocuments(IndexingProviderBase indexer) { IList <SearchDocument> searchDocs; System.Collections.ArrayList portals = PortalController.Instance.GetPortals(); DateTime indexSince; int indexedCount = 0; foreach (PortalInfo portal in portals.Cast <PortalInfo>()) { indexSince = FixedIndexingStartDate(portal.PortalID); try { indexedCount += indexer.IndexSearchDocuments( portal.PortalID, SchedulerItem, indexSince, StoreSearchDocuments); } catch (NotImplementedException) { #pragma warning disable 618 searchDocs = indexer.GetSearchDocuments(portal.PortalID, indexSince).ToList(); #pragma warning restore 618 StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } } // Include Host Level Items indexSince = FixedIndexingStartDate(-1); try { indexedCount += indexer.IndexSearchDocuments( Null.NullInteger, SchedulerItem, indexSince, StoreSearchDocuments); } catch (NotImplementedException) { #pragma warning disable 618 searchDocs = indexer.GetSearchDocuments(-1, indexSince).ToList(); #pragma warning restore 618 StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } return(indexedCount); }
public static void ConvertWithCast() { var list = new System.Collections.ArrayList(Formula1.GetChampions() as System.Collections.ICollection); /* * 需要在非类型化的集合上使用Linq查询,就可以使用Cast(); * * 下面基于Object类型的ArrayList集合用Racer对象填充。 * 为定义强类型化的查询,可使用Cast()方法。 */ var query = from r in list.Cast <Racer>() where r.Country == "USA" orderby r.Wins descending select r; foreach (var racer in query) { Console.WriteLine($"{racer:A}"); } }
public ActionResult Get([FromHeader] string InstanceCollection) { System.Collections.ArrayList InsCol = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.ArrayList>(InstanceCollection); List <InstanceContent> ContentListFromDB = (List <InstanceContent>)Contents.EntityCollection.Take(100000).OrderBy(c => c.Instance.Name).ToList(); List <string> Filter = InsCol.Cast <string>().ToList(); List <InstanceContent> ContentList = (from CL in ContentListFromDB.AsEnumerable() where Filter.Any(x => x.Contains(CL.Instance.Name)) select CL).ToList(); GalaxyObjects GObjcts = new GalaxyObjects(); GObjcts.List = ContentList; return(new ContentResult { Content = Newtonsoft.Json.JsonConvert.SerializeObject(GObjcts), ContentType = "application/json" }); }
public ActionResult GetSuggestUsers(int roleId, int count, string keyword) { ActionResult ActionResult = new ActionResult(); try { if (string.IsNullOrEmpty(keyword)) { return(ActionResult.Data = new List <UserRoleDto>()); } string displayMatch = keyword + "%"; int totalRecords = 0; int totalRecords2 = 0; bool isAdmin = UserManager.IsAdmin(PortalSettings); System.Collections.ArrayList matchedUsers = UserController.GetUsersByDisplayName(PortalSettings.PortalId, displayMatch, 0, count, ref totalRecords, false, false); matchedUsers.AddRange(UserController.GetUsersByUserName(PortalSettings.PortalId, displayMatch, 0, count, ref totalRecords2, false, false)); IEnumerable <UserRoleDto> finalUsers = matchedUsers .Cast <UserInfo>() .Where(x => isAdmin || !x.Roles.Contains(PortalSettings.AdministratorRoleName)) .Select(u => new UserRoleDto() { UserId = u.UserID, DisplayName = $"{u.DisplayName} ({u.Username})" }); ActionResult.Data = finalUsers.ToList().GroupBy(x => x.UserId).Select(group => group.First()); } catch (Exception ex) { ActionResult.AddError("HttpStatusCode.InternalServerError" + HttpStatusCode.InternalServerError, ex.Message); } return(ActionResult); }
private void Method() { var myArrayList = new System.Collections.ArrayList { System.Drawing.Color.Red, new System.Drawing.Point(0, 0), System.Drawing.Color.Green, new System.Drawing.Point(10, 20), System.Drawing.Color.Blue, new System.Drawing.Point(20, 30) }; var query1 = myArrayList.OfType <System.Drawing.Color>().Select(color => color); foreach (var currentResult in query1) { Console.WriteLine(currentResult.Name); } var procesArray = new System.Collections.ArrayList(); var query = procesArray.Cast <System.Diagnostics.Process>().Select(process => process); }
private static Dictionary <string, object> UploadCustomer(string psCustomerName, string psValue, string psFileName, int piCusOrderID) { //string lsReturnHashkey = ""; Dictionary <string, object> loReturn; WebRequest loWebRequest; WebResponse loWebResponse; JavaScriptSerializer loJson = new JavaScriptSerializer(); string lsMessage; string lsSQL; Dictionary <string, object> loJsonValue = new Dictionary <string, object> (); string lsJson = ""; try { loJsonValue.Add("property", "Trung Hung Tran"); loJsonValue.Add("customer", psCustomerName); loJsonValue.Add("action", "order created"); loJsonValue.Add("value", psValue); loJsonValue.Add("file", psFileName); loWebRequest = WebRequest.Create(msUploadURL); loWebRequest.Method = "POST"; loWebRequest.ContentType = "application/json"; lsJson = loJson.Serialize(loJsonValue); byte[] json = System.Text.Encoding.UTF8.GetBytes(lsJson); Stream requestStream = loWebRequest.GetRequestStream(); requestStream.Write(json, 0, json.Length); requestStream.Close(); try { loWebResponse = loWebRequest.GetResponse(); lsJson = new StreamReader(loWebResponse.GetResponseStream()) .ReadToEnd(); loReturn = loJson.Deserialize <Dictionary <string, object> >(lsJson); if (loReturn.ContainsKey("errors")) { System.Collections.ArrayList loError = (System.Collections.ArrayList)loReturn["errors"]; lsMessage = string.Join(", ", loError.Cast <string>().ToArray()) + ""; lsSQL = " update CustomerOrder set status ='{0} : {1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, loReturn["added"], ClsSQLite.FixStr(lsMessage), piCusOrderID)); } else if (loReturn.ContainsKey("hash")) { if (((string)loReturn["hash"]).Length == 32) { lsSQL = " update CustomerOrder set status ='{0}', hash ='{1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, loReturn["added"], ClsSQLite.FixStr((string)loReturn["hash"]), piCusOrderID)); } else { lsMessage = "Server Error Invalid hash return."; lsSQL = " update CustomerOrder set status ='{0} : {1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, "error", ClsSQLite.FixStr(lsMessage), piCusOrderID)); } } } catch (WebException wex) { lsJson = new StreamReader(wex.Response.GetResponseStream()) .ReadToEnd(); loReturn = loJson.Deserialize <Dictionary <string, object> >(lsJson); if (loReturn.ContainsKey("errors")) { System.Collections.ArrayList loError = (System.Collections.ArrayList)loReturn["errors"]; lsMessage = string.Join(", ", loError.Cast <string>().ToArray()); lsSQL = " update CustomerOrder set status ='{0} : {1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, "error", ClsSQLite.FixStr(lsMessage), piCusOrderID)); } } } catch (Exception ex) { lsSQL = " update CustomerOrder set status ='{0} : {1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, "error", ClsSQLite.FixStr(ex.Message), piCusOrderID)); loReturn = null; } return(loReturn); }
public static DataSet GetHashKey(string psHashKey) { DataSet loReturnDs = null; DataTable loLocalTb; DataTable loReturnTb; DataRow loReturnRow; Dictionary <string, object> loRemote; string lssql; // check from server loRemote = ClsEvilApi.CheckHashKey(psHashKey); loReturnDs = new DataSet(); loReturnTb = new DataTable("Hash Key from EVIL"); loReturnTb.Columns.Add("PropertyName"); loReturnTb.Columns.Add("Value"); foreach (string lskey in loRemote.Keys) { loReturnRow = loReturnTb.NewRow(); loReturnTb.Rows.Add(loReturnRow); loReturnRow[0] = lskey; if (lskey == "errors") { System.Collections.ArrayList loError = (System.Collections.ArrayList)loRemote["errors"]; loReturnRow[1] = string.Join(", ", loError.Cast <string>().ToArray()); } else { loReturnRow[1] = loRemote[lskey]; } } loReturnDs.Tables.Add(loReturnTb); //check from local lssql = "select * from CustomerOrder where Hash='{0}'"; if (psHashKey == null) { psHashKey = "N/A"; } loLocalTb = moDatabase.Query(String.Format(lssql, ClsSQLite.FixStr(psHashKey))); if (loLocalTb.Rows.Count > 0) { loReturnTb = new DataTable("Hash Key from local database."); loReturnTb.Columns.Add("PropertyName"); loReturnTb.Columns.Add("Value"); foreach (DataRow row in loLocalTb.Rows) { foreach (DataColumn col in loLocalTb.Columns) { loReturnRow = loReturnTb.NewRow(); loReturnTb.Rows.Add(loReturnRow); loReturnRow[0] = col.ColumnName; loReturnRow[1] = row[col.ColumnName]; } } loReturnDs.Tables.Add(loReturnTb); } return(loReturnDs); }
private static async System.Threading.Tasks.Task <Dictionary <string, object> > UploadCustomerAsync(string psCustomerName, string psValue, string psFileName, int piCusID) { Dictionary <string, object> loReturn; string lsMessage; Dictionary <string, object> loJsonValue = new Dictionary <string, object>(); JavaScriptSerializer loJson = new JavaScriptSerializer(); string lsJson = ""; string lsSQL; try { loJsonValue.Add("property", "Trung Hung Tran"); loJsonValue.Add("customer", psCustomerName); loJsonValue.Add("action", "order created"); loJsonValue.Add("value", psValue); loJsonValue.Add("file", psFileName); lsJson = loJson.Serialize(loJsonValue); try { using (var loClient = new HttpClient()) { loClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage loHttpRessult = await loClient.PostAsync(msUploadURL, new StringContent(lsJson)); lsJson = await loHttpRessult.Content.ReadAsStringAsync(); } loReturn = loJson.Deserialize <Dictionary <string, object> >(lsJson); if (loReturn.ContainsKey("errors")) { System.Collections.ArrayList loError = (System.Collections.ArrayList)loReturn["errors"]; lsMessage = string.Join(", ", loError.Cast <string>().ToArray()); lsSQL = " update CustomerOrder set status ='{0} : {1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, loReturn["added"], ClsSQLite.FixStr(lsMessage), piCusID)); } else if (loReturn.ContainsKey("hash")) { lsSQL = " update CustomerOrder set status ='{0}', hash ='{1}' where CusOrderID ={2} ; "; Library.ClsEvilApi.moDatabase.Exec(String.Format(lsSQL, loReturn["added"], ClsSQLite.FixStr((string)loReturn["hash"]), piCusID)); } } catch (WebException wex) { lsJson = new StreamReader(wex.Response.GetResponseStream()) .ReadToEnd(); loReturn = loJson.Deserialize <Dictionary <string, object> >(lsJson); } } catch { loReturn = null; } return(loReturn); }
private static string ToString(dynamic dyn) { if (dyn == null) { return("null"); } else { if (dyn is ValueType) { return(dyn.ToString()); } else { if (dyn is string) { return("'" + dyn + "'"); } else { if (dyn is System.Collections.IList) { var asList = new System.Collections.ArrayList(); foreach (var x in dyn) { asList.Add(ToString(x)); } return("[" + string.Join(", ", asList.Cast <string>()) + "]"); } else { if (dyn is System.Collections.IDictionary) { var asList = new System.Collections.ArrayList(); foreach (var x in dyn) { asList.Add(ToString(x.Key) + ": " + ToString(x.Value)); } return("{" + string.Join(", ", asList.Cast <string>()) + "}"); } } } } } var ret = new StringBuilder(); var first = true; ret.Append("{"); foreach (var r in dyn) { var key = r.Key; var val = r.Value; if (!first) { ret.Append(", "); } ret.Append(ToString(key) + ": " + ToString(val)); first = false; } ret.Append("}"); return(ret.ToString()); }
/// <summary> /// Given a filespec, find the files that match. /// Will never throw IO exceptions: if there is no match, returns the input verbatim. /// </summary> /// <param name="projectDirectoryUnescaped">The project directory.</param> /// <param name="filespecUnescaped">Get files that match the given file spec.</param> /// <param name="getFileSystemEntries">Get files that match the given file spec.</param> /// <param name="directoryExists">Determine whether a directory exists.</param> /// <returns>The array of files.</returns> internal static string[] GetFiles ( string projectDirectoryUnescaped, string filespecUnescaped, IEnumerable<string> excludeSpecsUnescaped, GetFileSystemEntries getFileSystemEntries, DirectoryExists directoryExists ) { // For performance. Short-circuit iff there is no wildcard. // Perf Note: Doing a [Last]IndexOfAny(...) is much faster than compiling a // regular expression that does the same thing, regardless of whether // filespec contains one of the characters. // Choose LastIndexOfAny instead of IndexOfAny because it seems more likely // that wildcards will tend to be towards the right side. if (!HasWildcards(filespecUnescaped)) { return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } // UNDONE (perf): Short circuit the complex processing when we only have a path and a wildcarded filename /* * Even though we return a string[] we work internally with an IList. * This is because it's cheaper to add items to an IList and this code * might potentially do a lot of that. */ System.Collections.ArrayList arrayListOfFiles = new System.Collections.ArrayList(); System.Collections.IList listOfFiles = (System.Collections.IList)arrayListOfFiles; /* * Analyze the file spec and get the information we need to do the matching. */ bool stripProjectDirectory; RecursionState state; var result = GetFileSearchData(projectDirectoryUnescaped, filespecUnescaped, getFileSystemEntries, directoryExists, out stripProjectDirectory, out state); if (result == GetSearchDataResult.ReturnEmptyList) { return new string[0]; } else if (result == GetSearchDataResult.ReturnFileSpec) { return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } else if (result != GetSearchDataResult.RunSearch) { // This means the enum value wasn't valid (or a new one was added without updating code correctly) throw new NotSupportedException(result.ToString()); } List<RecursionState> searchesToExclude = null; // Exclude searches which will become active when the recursive search reaches their BaseDirectory. // The BaseDirectory of the exclude search is the key for this dictionary. Dictionary<string, List<RecursionState>> searchesToExcludeInSubdirs = null; HashSet<string> resultsToExclude = null; if (excludeSpecsUnescaped != null) { searchesToExclude = new List<RecursionState>(); foreach (string excludeSpec in excludeSpecsUnescaped) { // This is ignored, we always use the include pattern's value for stripProjectDirectory bool excludeStripProjectDirectory; RecursionState excludeState; var excludeResult = GetFileSearchData(projectDirectoryUnescaped, excludeSpec, getFileSystemEntries, directoryExists, out excludeStripProjectDirectory, out excludeState); if (excludeResult == GetSearchDataResult.ReturnFileSpec) { if (resultsToExclude == null) { resultsToExclude = new HashSet<string>(); } resultsToExclude.Add(excludeSpec); } else if (excludeResult == GetSearchDataResult.ReturnEmptyList) { // Nothing to do continue; } else if (excludeResult != GetSearchDataResult.RunSearch) { // This means the enum value wasn't valid (or a new one was added without updating code correctly) throw new NotSupportedException(excludeResult.ToString()); } if (excludeState.BaseDirectory != state.BaseDirectory) { // What to do if the BaseDirectory for the exclude search doesn't match the one for inclusion? // - If paths don't match (one isn't a prefix of the other), then ignore the exclude search. Examples: // - c:\Foo\ - c:\Bar\ // - c:\Foo\Bar\ - C:\Foo\Baz\ // - c:\Foo\ - c:\Foo2\ if (excludeState.BaseDirectory.Length == state.BaseDirectory.Length) { // Same length, but different paths. Ignore this exclude search continue; } else if (excludeState.BaseDirectory.Length > state.BaseDirectory.Length) { if (!excludeState.BaseDirectory.StartsWith(state.BaseDirectory)) { // Exclude path is longer, but doesn't start with include path. So ignore it. continue; } // - The exclude BaseDirectory is somewhere under the include BaseDirectory. So // keep the exclude search, but don't do any processing on it while recursing until the baseDirectory // in the recursion matches the exclude BaseDirectory. Examples: // - Include - Exclude // - C:\git\msbuild\ - c:\git\msbuild\obj\ // - C:\git\msbuild\ - c:\git\msbuild\src\Common\ if (searchesToExcludeInSubdirs == null) { searchesToExcludeInSubdirs = new Dictionary<string, List<RecursionState>>(); } List<RecursionState> listForSubdir; if (!searchesToExcludeInSubdirs.TryGetValue(excludeState.BaseDirectory, out listForSubdir)) { listForSubdir = new List<RecursionState>(); searchesToExcludeInSubdirs[excludeState.BaseDirectory] = listForSubdir; } listForSubdir.Add(excludeState); } else { // Exclude base directory length is less than include base directory length. if (!state.BaseDirectory.StartsWith(excludeState.BaseDirectory)) { // Include path is longer, but doesn't start with the exclude path. So ignore exclude path // (since it won't match anything under the include path) continue; } // Now check the wildcard part if (excludeState.RemainingWildcardDirectory.Length == 0) { // The wildcard part is empty, so ignore the exclude search, as it's looking for files non-recursively // in a folder higher up than the include baseDirectory. // Example: include="c:\git\msbuild\src\Framework\**\*.cs" exclude="c:\git\msbuild\*.cs" continue; } else if (excludeState.RemainingWildcardDirectory == recursiveDirectoryMatch + s_directorySeparator) { // The wildcard part is exactly "**\", so the exclude pattern will apply to everything in the include // pattern, so simply update the exclude's BaseDirectory to be the same as the include baseDirectory // Example: include="c:\git\msbuild\src\Framework\**\*.*" exclude="c:\git\msbuild\**\*.bak" excludeState.BaseDirectory = state.BaseDirectory; searchesToExclude.Add(excludeState); } else { // The wildcard part is non-empty and not "**\", so we will need to match it with a Regex. Fortunately // these conditions mean that it needs to be matched with a Regex anyway, so here we will update the // BaseDirectory to be the same as the exclude BaseDirectory, and change the wildcard part to be "**\" // because we don't know where the different parts of the exclude wildcard part would be matched. // Example: include="c:\git\msbuild\src\Framework\**\*.*" exclude="c:\git\msbuild\**\bin\**\*.*" Debug.Assert(excludeState.SearchData.RegexFileMatch != null, "Expected Regex to be used for exclude file matching"); excludeState.BaseDirectory = state.BaseDirectory; excludeState.RemainingWildcardDirectory = recursiveDirectoryMatch + s_directorySeparator; searchesToExclude.Add(excludeState); } } } else { searchesToExclude.Add(excludeState); } } } if (searchesToExclude != null && searchesToExclude.Count == 0) { searchesToExclude = null; } /* * Now get the files that match, starting at the lowest fixed directory. */ try { GetFilesRecursive(listOfFiles, state, projectDirectoryUnescaped, stripProjectDirectory, getFileSystemEntries, searchesToExclude, searchesToExcludeInSubdirs); } catch (Exception ex) when (ExceptionHandling.IsIoRelatedException(ex)) { // Assume it's not meant to be a path return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } /* * Build the return array. */ string[] files; if (resultsToExclude != null) { files = arrayListOfFiles.Cast<string>().Where(f => !resultsToExclude.Contains(f)).ToArray(); } else { files = (string[])arrayListOfFiles.ToArray(typeof(string)); } return files; }