9866550012
CSHARP LINQ OPERATIONSclass FindSentences { static void Main() { string text = @"Historically, the world of data and the world of objects " + @"have not been well integrated. Programmers work in C# or Visual Basic " + @"and also in SQL or XQuery. On the one side are concepts such as classes, " + @"objects, fields, inheritance, and .NET Framework APIs. On the other side " + @"are tables, columns, rows, nodes, and separate languages for dealing with " + @"them. Data types often require translation between the two worlds; there are " + @"different standard functions. Because the object world has no notion of query, a " + @"query can only be represented as a string without compile-time type checking or " + @"IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " + @"objects in memory is often tedious and error-prone."; // Split the text block into an array of sentences. string[] sentences = text.Split(new char[] { '.', '?', '!' }); // Define the search terms. This list could also be dynamically populated at runtime. string[] wordsToMatch = { "Historically", "data", "integrated" }; // Find sentences that contain all the terms in the wordsToMatch array. // Note that the number of terms to match is not specified at compile time. var sentenceQuery = from sentence in sentences let w = sentence.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries) where w.Distinct().Intersect(wordsToMatch).Count() == wordsToMatch.Count() select sentence; // Execute the query. Note that you can explicitly type // the iteration variable here even though sentenceQuery // was implicitly typed. foreach (string str in sentenceQuery) { Console.WriteLine(str); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } /* Output: Historically, the world of data and the world of objects have not been well integrated */
class CountWords { static void Main() { string text = @"Historically, the world of data and the world of objects" + @" have not been well integrated. Programmers work in C# or Visual Basic" + @" and also in SQL or XQuery. On the one side are concepts such as classes," + @" objects, fields, inheritance, and .NET Framework APIs. On the other side" + @" are tables, columns, rows, nodes, and separate languages for dealing with" + @" them. Data types often require translation between the two worlds; there are" + @" different standard functions. Because the object world has no notion of query, a" + @" query can only be represented as a string without compile-time type checking or" + @" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" + @" objects in memory is often tedious and error-prone."; string searchTerm = "data"; //Convert the string into an array of words string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); // Create and execute the query. It executes immediately // because a singleton value is produced. // Use ToLowerInvariant to match "data" and "Data" var matchQuery = from word in source where word.ToLowerInvariant() == searchTerm.ToLowerInvariant() select word; // Count the matches. int wordCount = matchQuery.Count(); Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCount, searchTerm); // Keep console window open in debug mode Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } /* Output: 3 occurrences(s) of the search term "data" were found. */
class QueryAString { static void Main() { string aString = "ABCDE99F-J74-12-89A"; // Select only those characters that are numbers IEnumerable<char> stringQuery = from ch in aString where Char.IsDigit(ch) select ch; // Execute the query foreach (char c in stringQuery) Console.Write(c + " "); // Call the Count method on the existing query. int count = stringQuery.Count(); Console.WriteLine("Count = {0}", count); // Select all characters before the first '-' IEnumerable<char> stringQuery2 = aString.TakeWhile(c => c != '-'); // Execute the second query foreach (char c in stringQuery2) Console.Write(c); Console.WriteLine(System.Environment.NewLine + "Press any key to exit"); Console.ReadKey(); } } /* Output: Output: 9 9 7 4 1 2 8 9 Count = 8 ABCDE99F */
class QueryWithRegEx { public static void Main() { // Modify this path as necessary. string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\"; // Take a snapshot of the file system. IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder); // Create the regular expression to find all things "Visual". System.Text.RegularExpressions.Regex searchTerm = new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C\+\+|J#|SourceSafe|Studio)"); // Search the contents of each .htm file. // Remove the where clause to find even more matches! // This query produces a list of files where a match // was found, and a list of the matches in that file. // Note: Explicit typing of "Match" in select clause. // This is required because MatchCollection is not a // generic IEnumerable collection. var queryMatchingFiles = from file in fileList where file.Extension == ".htm" let fileText = System.IO.File.ReadAllText(file.FullName) let matches = searchTerm.Matches(fileText) where searchTerm.Matches(fileText).Count > 0 select new { name = file.FullName, matches = from System.Text.RegularExpressions.Match match in matches select match.Value }; // Execute the query. Console.WriteLine("The term \"{0}\" was found in:", searchTerm.ToString()); foreach (var v in queryMatchingFiles) { // Trim the path a bit, then write // the file name in which a match was found. string s = v.name.Substring(startFolder.Length - 1); Console.WriteLine(s); // For this file, write out all the matching strings foreach (var v2 in v.matches) { Console.WriteLine(" " + v2); } } // Keep the console window open in debug mode Console.WriteLine("Press any key to exit"); Console.ReadKey(); } // This method assumes that the application has discovery // permissions for all folders under the specified path. static IEnumerable<System.IO.FileInfo> GetFiles(string path) { if (!System.IO.Directory.Exists(path)) throw new System.IO.DirectoryNotFoundException(); string[] fileNames = null; List<System.IO.FileInfo> files = new List<System.IO.FileInfo>(); fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories); foreach (string name in fileNames) { files.Add(new System.IO.FileInfo(name)); } return files; } }
class CompareLists { static void Main() { // Create the IEnumerable data sources. string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt"); string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt"); // Create the query. Note that method syntax must be used here. IEnumerable<string> differenceQuery = names1.Except(names2); // Execute the query. Console.WriteLine("The following lines are in names1.txt but not names2.txt"); foreach (string s in differenceQuery) Console.WriteLine(s); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } /* Output: The following lines are in names1.txt but not names2.txt Potra, Cristina Noriega, Fabricio Aw, Kam Foo Toyoshima, Tim Guy, Wey Yuan Garcia, Debra */
public class SortLines { static void Main() { // Create an IEnumerable data source string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv"); // Change this to any value from 0 to 4. int sortField = 1; Console.WriteLine("Sorted highest to lowest by field [{0}]:", sortField); // Demonstrates how to return query from a method. // The query is executed here. foreach (string str in RunQuery(scores, sortField)) { Console.WriteLine(str); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit"); Console.ReadKey(); } // Returns the query variable, not query results! static IEnumerable<string> RunQuery(IEnumerable<string> source, int num) { // Split the string and sort on field[num] var scoreQuery = from line in source let fields = line.Split(',') orderby fields[num] descending select line; return scoreQuery; } } /* Output (if sortField == 1): Sorted highest to lowest by field [1]: 116, 99, 86, 90, 94 120, 99, 82, 81, 79 111, 97, 92, 81, 60 114, 97, 89, 85, 82 121, 96, 85, 91, 60 122, 94, 92, 91, 91 117, 93, 92, 80, 87 118, 92, 90, 83, 78 113, 88, 94, 65, 91 112, 75, 84, 91, 39 119, 68, 79, 88, 92 115, 35, 72, 91, 70 */
- Create a new Visual C# or Visual Basic project and copy the following lines into a plain text file that is named spreadsheet1.csv. Save the file in your solution folder.
Adams,Terry,120 Fakhouri,Fadi,116 Feng,Hanying,117 Garcia,Cesar,114 Garcia,Debra,115 Garcia,Hugo,118 Mortensen,Sven,113 O'Donnell,Claire,112 Omelchenko,Svetlana,111 Tucker,Lance,119 Tucker,Michael,122 Zabokritski,Eugene,121
class CSVFiles { static void Main(string[] args) { // Create the IEnumerable data source string[] lines = System.IO.File.ReadAllLines(@"../../../spreadsheet1.csv"); // Create the query. Put field 2 first, then // reverse and combine fields 0 and 1 from the old field IEnumerable<string> query = from line in lines let x = line.Split(',') orderby x[2] select x[2] + ", " + (x[1] + " " + x[0]); // Execute the query and write out the new file. Note that WriteAllLines // takes a string[], so ToArray is called on the query. System.IO.File.WriteAllLines(@"../../../spreadsheet2.csv", query.ToArray()); Console.WriteLine("Spreadsheet2.csv written to disk. Press any key to exit"); Console.ReadKey(); } } /* Output to spreadsheet2.csv: 111, Svetlana Omelchenko 112, Claire O'Donnell 113, Sven Mortensen 114, Cesar Garcia 115, Debra Garcia 116, Fadi Fakhouri 117, Hanying Feng 118, Hugo Garcia 119, Lance Tucker 120, Terry Adams 121, Eugene Zabokritski 122, Michael Tucker */
To set up the project and the text files
Copy these names into a text file that is named names1.txt and save it in your solution folder:Bankov, Peter Holm, Michael Garcia, Hugo Potra, Cristina Noriega, Fabricio Aw, Kam Foo Beebe, Ann Toyoshima, Tim Guy, Wey Yuan Garcia, Debra Copy these names into a text file that is named names2.txt and save it in your solution folder. Note that the two files have some names in common.Liu, Jinghao Bankov, Peter Holm, Michael Garcia, Hugo Beebe, Ann Gilchrist, Beth Myrcha, Jacek Giakoumakis, Leo McLin, Nkenge El Yassir, Mehdi
class MergeStrings { static void Main(string[] args) { //Put text files in your solution folder string[] fileA = System.IO.File.ReadAllLines(@"../../../names1.txt"); string[] fileB = System.IO.File.ReadAllLines(@"../../../names2.txt"); //Simple concatenation and sort. Duplicates are preserved. IEnumerable<string> concatQuery = fileA.Concat(fileB).OrderBy(s => s); // Pass the query variable to another function for execution. OutputQueryResults(concatQuery, "Simple concatenate and sort. Duplicates are preserved:"); // Concatenate and remove duplicate names based on // default string comparer. IEnumerable<string> uniqueNamesQuery = fileA.Union(fileB).OrderBy(s => s); OutputQueryResults(uniqueNamesQuery, "Union removes duplicate names:"); // Find the names that occur in both files (based on // default string comparer). IEnumerable<string> commonNamesQuery = fileA.Intersect(fileB); OutputQueryResults(commonNamesQuery, "Merge based on intersect:"); // Find the matching fields in each list. Merge the two // results by using Concat, and then // sort using the default string comparer. string nameMatch = "Garcia"; IEnumerable<String> tempQuery1 = from name in fileA let n = name.Split(',') where n[0] == nameMatch select name; IEnumerable<string> tempQuery2 = from name2 in fileB let n2 = name2.Split(',') where n2[0] == nameMatch select name2; IEnumerable<string> nameMatchQuery = tempQuery1.Concat(tempQuery2).OrderBy(s => s); OutputQueryResults(nameMatchQuery, String.Format("Concat based on partial name match \"{0}\":", nameMatch)); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit"); Console.ReadKey(); } static void OutputQueryResults(IEnumerable<string> query, string message) { Console.WriteLine(System.Environment.NewLine + message); foreach (string item in query) { Console.WriteLine(item); } Console.WriteLine("{0} total names in list", query.Count()); } } /* Output: Simple concatenate and sort. Duplicates are preserved: Aw, Kam Foo Bankov, Peter Bankov, Peter Beebe, Ann Beebe, Ann El Yassir, Mehdi Garcia, Debra Garcia, Hugo Garcia, Hugo Giakoumakis, Leo Gilchrist, Beth Guy, Wey Yuan Holm, Michael Holm, Michael Liu, Jinghao McLin, Nkenge Myrcha, Jacek Noriega, Fabricio Potra, Cristina Toyoshima, Tim 20 total names in list Union removes duplicate names: Aw, Kam Foo Bankov, Peter Beebe, Ann El Yassir, Mehdi Garcia, Debra Garcia, Hugo Giakoumakis, Leo Gilchrist, Beth Guy, Wey Yuan Holm, Michael Liu, Jinghao McLin, Nkenge Myrcha, Jacek Noriega, Fabricio Potra, Cristina Toyoshima, Tim 16 total names in list Merge based on intersect: Bankov, Peter Holm, Michael Garcia, Hugo Beebe, Ann 4 total names in list Concat based on partial name match "Garcia": Garcia, Debra Garcia, Hugo Garcia, Hugo 3 total names in list */
No comments:
Post a Comment