static void Main() { var collection = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; int first = collection.FirstOrDefault(Even); Console.WriteLine(first); Console.WriteLine(collection.FirstOrDefault(x => x > 4)); var allEven = collection.TakeWhile(Even); Console.WriteLine(string.Join(" ",allEven)); Console.WriteLine(string.Join(" ", collection.TakeWhile(x => x < 10))); collection.ForEach(Console.WriteLine); }
static void Main() { List<int> collection = new List<int>() { 1, 2, 3, 6, 11, 20 }; Console.WriteLine(collection.FirstOrDefault(x => x > 7)); Console.WriteLine(string.Join(", ", collection.TakeWhile(x => x < 5))); collection.ForEach(Console.WriteLine); }
static void Main(string[] args) { var nums = new List<int>() {1, 2, 3, 4, 5, 6, 7}; var result = nums.TakeWhile(e => e < 6); Console.WriteLine(string.Join(", ", result)); }
private static List<Solution> filterByEnding(Solution end, List<Solution> solutions) { if (end != null) { solutions = solutions.TakeWhile(x => x != end).Where(end.DependsOn).ToList(); solutions.Add(end); } return solutions; }
public ProductRepository() { _products = new List<Product>(new Product[]{ new Product {Name = "Kayak", Category = "Watersports", Price = 275M}, new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M}, new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M}, new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M} }); _products.TakeWhile(p => p.Name == "Kayak"); }
public JsonResult Lista() { var lista = new List<int> (); for (int i = 0; i < 50; i++) { lista.Add (i); } var tes = lista.TakeWhile(a => a < 15).LastOrDefault(); return Json(tes, JsonRequestBehavior.AllowGet); }
public static IEnumerable<ulong> UlongPrimes() { var memoized = new List<ulong>(); var primes = PotentialUlongPrimes().Where(x => { double sqrt = Math.Sqrt(x); return memoized .TakeWhile(y => y <= sqrt) .All(y => x % y != 0); }); foreach (var prime in primes) { yield return prime; memoized.Add(prime); } }
static void Main() { List<int> list = new List<int>() { 1, 12, 19, 13, 100, 1, 1000, 13, 13, 1 }; IEnumerable<int> smallNums = list.TakeWhile(n => n < 100); foreach (var num in smallNums) { Console.WriteLine(num); } }
public static IEnumerable<int> Primes4(int count) { var memoized = new List<int>(); var primes = PotentialPrimes(count).Where(x => { var sqrt = Math.Sqrt(x); return !memoized .TakeWhile(y => y <= sqrt) .Any(y => x % y == 0); }); foreach (var prime in primes) { yield return prime; memoized.Add(prime); } }
public int Delete(string name, string producer) { var productsWithGivenName = new List<Product>( productsByName[name]); var temp = productsWithGivenName.TakeWhile(x => x.Producer == producer); var count = temp.Count(); foreach (var product in temp) { productsByName.Remove(product.Name); productsByPrice.Remove(product); productsByProducer.Remove(producer); } return count; }
public static IEnumerable <long> Get () { var temp = new List <long> (); var current = 1L; while (true) { current++; var sqrt = Math.Sqrt (current); if (temp .TakeWhile (x => x <= sqrt) .Any (x => current % x == 0)) continue; temp.Add (current); yield return current; } }
static void Main() { Action<int> printNumberAction = Console.WriteLine; printNumberAction(10); var students = new List<Student>() { new Student("Pesho", 23), new Student("Sasho", 18), new Student("Ivan", 34) }; Student ivan = students.FirstOrDef(Hasname); Console.WriteLine(ivan.Name + " " + ivan.Age); var nums = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; nums.ForEachH(); var smallNums = nums.TakeWhile(IsSmallerThan); Console.WriteLine(String.Join(", ", smallNums)); }
public void Append(TableDataDesc table) { var rows = new List<RowDesc>(); foreach(var scriptedRow in table.ScriptedData) { var row = DataDescFactory.CreateRowDescriptor(scriptedRow, table.PrimaryColumns); rows.Add(row); } var gen = new RowScriptGen(); //Header var header = rows.TakeWhile(r => false == r is InsertRowDesc); //_sb.Append(gen.GenerateScript(header)); _sb.AppendFormat("{0}{1}", gen.GenerateScript(header), Environment.NewLine); //Data var data = rows.Where(r => r is InsertRowDesc).Select(r => r as InsertRowDesc); _sb.AppendFormat("{0}{1}", gen.GenerateMergeScript(data, true), Environment.NewLine); //Footer var footer = rows.Skip(header.Count() + data.Count()); _sb.AppendFormat("{0}{1}", gen.GenerateScript(footer), Environment.NewLine); }
private IList<Rectangle> ProbeScreenBounds() { var screenBoundsList = new List<Rectangle>(); foreach (Screen screen in Screen.AllScreens) { Rectangle currentBounds = DpiHelper.ConvertPixelsToDIPixels(screen.Bounds); if (screenBoundsList.Count == 0) { screenBoundsList.Add(currentBounds); continue; } int index = screenBoundsList.TakeWhile(bounds => (currentBounds.Top >= bounds.Top) && (currentBounds.Left >= bounds.Left)).Count(); screenBoundsList.Insert(index, currentBounds); } return screenBoundsList; }
public IEnumerable<long> Generate() { var primes = new List<long>(); yield return 2; yield return 3; var value = 5L; var add4 = false; while(true) { var maxFactor = (int)Math.Sqrt(value) + 1; if (!primes.TakeWhile(prime => prime <= maxFactor).Any(prime => value % prime == 0)) { primes.Add(value); yield return value; } value += (add4 ? 4 : 2); add4 = !add4; } }
public IViewComponentResult Invoke(string linqQueryType) { var modelList = new List<SampleModel>() { new SampleModel { Prop1 = "Hello", Prop2 = "World" }, new SampleModel { Prop1 = linqQueryType, Prop2 = "Test" }, }; switch (linqQueryType) { case "Where": return View(modelList.Where(e => e != null)); case "Take": return View(modelList.Take(2)); case "TakeWhile": return View(modelList.TakeWhile(a => a != null)); case "Union": return View(modelList.Union(modelList)); case "SelectMany": var selectManySampleModelList = new List<SelectManySampleModel> { new SelectManySampleModel { TestModel = new List<SampleModel> { new SampleModel { Prop1 = "Hello", Prop2 = "World" } } }, new SelectManySampleModel { TestModel = new List<SampleModel> { new SampleModel{ Prop1 = linqQueryType, Prop2 = "Test" } } } }; return View(selectManySampleModelList.SelectMany(a => a.TestModel)); }; return View(modelList.Select(e => e)); }
/// <summary> /// Extracts images for a page and linked pages. /// </summary> /// <param name="method">Method which extracts images from speicific Uri.</param> /// <param name="uri">Uri to extract images and start hyperlink recursion from.</param> /// <param name="settings">Extraction Settings.</param> /// <param name="depth">Depth to recurse hyperlinks to.</param> /// <returns>Returns extracted images for given Uri and linked pages.</returns> public static async Task <List <WebImage> > HyperlinkRecurse(ExtractionMethod method, Uri uri, ExtractionSettings settings, int depth) { HtmlDocument doc = null; bool gotDoc = false; List <WebImage> images = new List <WebImage>(); if (!exploredUris.Contains(uri.ToString())) { exploredUris.Add(uri.ToString()); if (settings.OnStartNewPage != null) { await settings.OnStartNewPage.Invoke(uri.ToString()); } gotDoc = true; doc = await GetDocumnent(uri); images = await method.Invoke(uri, doc, settings); if (settings.OnEndNewPage != null) { await settings.OnEndNewPage.Invoke(uri.ToString(), images); } if (settings.ShouldStopOnFoundImage != null) { // Take all images up to the point where should stop int index = images.TakeWhile(i => !settings.ShouldStopOnFoundImage.Invoke(i)).Count(); if (index != images.Count) { images.RemoveRange(index + 1, images.Count - index - 1); stopAlg = true; } } if (!settings.LazyDownload) { await Task.WhenAll(images.Select(i => i.GetImageAsync()).ToArray()); } if (settings.OnFoundImage != null) { images.ForEach(i => settings.OnFoundImage.Invoke(i)); } } if (!stopAlg && settings.RecurseHyperlinks && depth < settings.HyperlinkRecursionDepth) { if (!gotDoc) { doc = await GetDocumnent(uri); } if (doc != null) { IEnumerable <HtmlATag> aTags = HtmlExtractor.ExtractATags(doc); foreach (HtmlATag aTag in aTags) { Uri newUri = uri.AddHtmlLink(aTag.Href); List <WebImage> moreImages = await HyperlinkRecurse(method, newUri, settings, depth + 1); images.AddRange(moreImages); } } } return(images); }
/// <summary> /// Sees if application exists /// </summary> /// <param name="appName">Application Name</param> /// <returns>True if it exists</returns> private static bool AppExists(string appName) { var regKeysList = new List <RegistryKey>(); Utils.SafeOpenRegistryKey(() => regKeysList.Add(Registry.ClassesRoot.OpenSubKey("Applications"))); Utils.SafeOpenRegistryKey( () => regKeysList.Add(Registry.LocalMachine.OpenSubKey(@"Software\Classes\Applications"))); Utils.SafeOpenRegistryKey( () => regKeysList.Add(Registry.CurrentUser.OpenSubKey(@"Software\Classes\Applications"))); if (Utils.Is64BitOs) { Utils.SafeOpenRegistryKey( () => regKeysList.Add(Registry.ClassesRoot.OpenSubKey(@"Wow6432Node\Applications"))); Utils.SafeOpenRegistryKey( () => regKeysList.Add(Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\Classes\Applications"))); Utils.SafeOpenRegistryKey( () => regKeysList.Add(Registry.CurrentUser.OpenSubKey(@"Software\Wow6432Node\Classes\Applications"))); } try { foreach (var rk in regKeysList.TakeWhile(rk => !CancellationToken.IsCancellationRequested)) { if (rk == null) { continue; } RegistryKey subKey = null; try { subKey = rk.OpenSubKey(appName); if (subKey != null) { if (!Wizard.IsOnIgnoreList(appName)) { return(true); } } } catch (Exception ex) { Debug.WriteLine("The following error occurred: " + ex.Message + "\nSkipping check for AppName"); } finally { subKey?.Close(); } } } catch { return(false); } return(false); }
/// <summary> /// Sends message (from template in parameter) /// </summary> /// <param name="package">Package with initial data</param> public void SendPackage(Package package) { // Divide to packages var packages = new List<Package>(); _messages.Add(new Package { Id = FreeId, MessageCreatedOn = TickNumber }); if (package.SizeTotal() <= SizeMaxPackage) // If message is in size like one package { package.FromNow = package.From; package.Id = FreeId; package.MyBufIdx = Nodes[package.From].Buffer.Count; package.Sent = 0; package.PartIdx = 0; package.TickGeneratedOn = TickNumber; // For statistics package.CreatedOn = TickNumber; // For statistics packages.Add(package); SendedMessagePart = 1; // For external world if (package.IsDatagram) DatagramsSent++; else VirtualSent++; } else // If bigger { // Divide message to packages var sizeMaxInf = SizeMaxPackage - Package.SizeHeader; var packagesNumber = Convert.ToInt32(Math.Ceiling(package.SizeInformation / (double)sizeMaxInf)); if (package.IsDatagram) DatagramsSent += packagesNumber; else VirtualSent += packagesNumber; SendedMessagePart = packagesNumber; // For external world var firstBufIdx = Nodes[package.From].Buffer.Count; for (var i = 0; i < packagesNumber - 1; i++) // Several the same packages packages.Add(new Package { To = package.To, FromNow = package.From, From = package.From, IsDatagram = package.IsDatagram, Id = FreeId, PartIdx = i, SizeInformation = sizeMaxInf, MyBufIdx = firstBufIdx + i, Sent = 0, Parts = packagesNumber, TickGeneratedOn = TickNumber, // For statistics CreatedOn = TickNumber // For statistics }); // Last package can be lesser in size var sizeLastInf = package.SizeInformation % sizeMaxInf; packages.Add(new Package { To = package.To, FromNow = package.From, From = package.From, IsDatagram = package.IsDatagram, Id = FreeId, PartIdx = packagesNumber - 1, SizeInformation = sizeLastInf, MyBufIdx = firstBufIdx + packagesNumber - 1, Sent = 0, Parts = packagesNumber, TickGeneratedOn = TickNumber, // For statistics CreatedOn = TickNumber // For statistics }); } // Add packages while it isn't filled foreach (var pack in packages.TakeWhile(pack => BufferSize > Nodes[package.From].Buffer.Count)) Nodes[package.From].Buffer.Add(pack); // Add new packages to buffer //Nodes[package.From].Buffer.AddRange(packages); FreeId++; }
static void Main(string[] args) { //Restriction/Filtering Operations // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from fruit in fruits where fruit[0] == 'L' select fruit; LFruits.ToList().ForEach(fruit => Console.WriteLine(fruit)); // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(number => number % 6 == 0 || number % 4 == 0); fourSixMultiples.ToList().ForEach(number => Console.WriteLine(number)); //Ordering Operations // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable <string> decendingNames = from name in names orderby name descending select name; decendingNames.ToList().ForEach(name => Console.WriteLine(name)); // Build a collection of these numbers sorted in ascending order List <int> nums = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> numbsAscending = from num in nums orderby num ascending select num; numbsAscending.ToList().ForEach(num => Console.WriteLine(num)); //Aggregate Operations // Output how many numbers are in this list List <int> numbies = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int amountOfNumbers = numbies.Count(); Console.WriteLine(amountOfNumbers); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double total = purchases.Sum(); Console.WriteLine(total); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double mostExpensiveProduct = prices.Max(); Console.WriteLine(mostExpensiveProduct); //Partitioning Operations /* * Store each number in the following List until a perfect square * is detected. * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; IEnumerable <int> n = wheresSquaredo.TakeWhile(num => { int number = Convert.ToInt32(Math.Sqrt(num)); return(number * number != num); }); n.ToList().ForEach(num => Console.WriteLine(num)); /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq * Example Output: * WF 2 * BOA 1 * FTB 1 * CITI 1 */ // create some banks and store them in a list List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; // create some customers and store them in a list List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; IEnumerable <Customer> millionaires = customers.Where(customer => customer.Balance >= 1000000); var Banks = millionaires.GroupBy(customer => customer.Bank); foreach (IGrouping <string, Customer> millionBoys in Banks) { Console.WriteLine($"{millionBoys.Key} {millionBoys.Count()}"); } }
public static int GetRepetitionIndex(this ParseParsedIndex i, List<ParsedElement> allParsedElements) { //incidentally, this method computes exactly the same as ParseParsedIndex.GetRepetitionIndex(NotationMatch<TDomain>, RepetitionParseForm) but in a completely different manner return allParsedElements.TakeWhile(parsedElement => parsedElement.ParseIndex < i).Count(parsedElement => parsedElement.ParseIndex.Element == i.Element); }
float ComputePosY(ref List<Txt> txts) { // Considering a vertical margin of 15% of the height float Y = 0; var heightMargin = (float)MetroSlideshow.WindowHeight * 0.15; var stackHeightTextOnTopItThis = txts.TakeWhile(x => x.Id < Id).Sum(x => x.RowHeight); Y = (float)heightMargin + stackHeightTextOnTopItThis; return Y; }
private static List<EventListModel> SortAndLimitTo20(List<EventListModel> upcomingEvents) { upcomingEvents.Sort((e1, e2) => e1.Date.CompareTo(e2.Date)); var upcomingEventsLimited = new List<EventListModel>(); int[] counter = { 0 }; foreach (var upcomingEvent in upcomingEvents.TakeWhile(upcomingEvent => counter[0] < 20)) { upcomingEventsLimited.Add(upcomingEvent); counter[0]++; } return upcomingEventsLimited; }
static void Main(string[] args) { Console.WriteLine("Hello World!"); List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; // Using Custom Types List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; IEnumerable <Customer> richPeople = from peeps in customers where peeps.Balance >= 1000000 select peeps; // foreach (Customer person in richPeople) { // Console.WriteLine($"{person.Name} has ${person.Balance} in {person.Bank}"); // } IEnumerable <Customer> millionaires = customers.GroupBy(y => y.Bank); // foreach(var bank in millionaires) { // Console.WriteLine(bank.Key + " : " + bank.Count(y => y.Balance >= 1000000)); // } var millionaireReport = from c in customers where c.Balance >= 1000000 join b in banks on c.Bank equals b.Symbol select new { Bank = b.Name, Money = c.Balance }; // richPeople.Join(bankList, Key => richPeople, Bank => bankList); foreach (var customer in millionaireReport) { Console.WriteLine($"{customer.Bank} has a customer with a balance of ${customer.Money}"); } // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from fruit in fruits // where fruit.Substring(0, 1) == ("L") where fruit.StartsWith("L") select fruit; // Console.WriteLine($"Here are the L Fruits"); foreach (var l in LFruits) { // Console.WriteLine($"{l}"); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where((digit) => digit % 4 == 0 || digit % 6 == 0); foreach (int thing in fourSixMultiples) { // Console.WriteLine(thing); } List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable <string> descend = from name in names orderby name descending select name; foreach (string name in descend) { // Console.WriteLine(name); } // Build a collection of these numbers sorted in ascending order List <int> newNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> ascend = from num in newNumbers orderby num ascending select num; foreach (int num in ascend) { // Console.WriteLine(num); } // Output how many numbers are in this list List <int> numbers2 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int numCount = numbers2.Count(); // Console.WriteLine(numCount); List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double totalPrice = purchases.Sum(); // Console.WriteLine($"${totalPrice}"); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double priciest = prices.Max(); // Console.WriteLine(priciest); /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; IEnumerable <int> notSquare = wheresSquaredo.TakeWhile((num) => Math.Sqrt(num) % 1 != 0); foreach (var i in notSquare) { // Console.WriteLine(i); } }
static void Main(string[] args) { // Restriction/Filtering Operations // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> startsWithL = from fruit in fruits where fruit.StartsWith("L") select fruit; foreach (string fruit in startsWithL) { Console.WriteLine($"{fruit}"); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; var fourSixMultiples = numbers.Where(number => (number % 4 == 0) || (number % 6 == 0)); foreach (int number in fourSixMultiples) { Console.WriteLine($"{number}"); } // Ordering Operations // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; var descendingNames = names.OrderByDescending(name => name); foreach (string name in descendingNames) { Console.WriteLine($"{name}"); } // Build a collection of these numbers sorted in ascending order List <int> numbers1 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; var ascendingNumbers = numbers1.OrderBy(number => number); foreach (int number in ascendingNumbers) { Console.WriteLine($"{number}"); } // Aggregate Operators // Output how many numbers are in this list List <int> numbers2 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; var numberCount = numbers2.Count; Console.WriteLine(numberCount); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; var numberSum = purchases.Sum(purchase => purchase); Console.WriteLine(numberSum); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; var maxDouble = prices.Max(); Console.WriteLine(maxDouble); // Partitioning Operations // //Store each number in the following List until a perfect square is detected. List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; var runSquares = wheresSquaredo.TakeWhile(taco => Math.Sqrt(taco) % 1 != 0); foreach (int number in runSquares) { Console.WriteLine(number); } // // Build a collection of customers who are millionaires // // Given the same customer set, display how many millionaires per bank. List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; var millionaires = from customer in customers // can use var for linq statements in IEnumerable lists where customer.Balance >= 1000000 select customer; foreach (var customer in millionaires) { Console.WriteLine($"{customer.Name} {customer.Balance}"); } var millGroup = from millionaire in millionaires group millionaire by millionaire.Bank into taco select new { Bank = taco.Key, Customers = taco }; var grouped = customers.Where(c => c.Balance >= 1000000) // what goes into grouped is millionaire customers .GroupBy(d => d.Bank); foreach (var potato in grouped) { Console.WriteLine($"{potato.Key} {potato.Count()}"); foreach (var customer in potato) { Console.WriteLine($" {customer.Name} {customer.Balance}"); } } // TASK: As in the previous exercise, you're going to output the millionaires, // but you will also display the full name of the bank. You also need to sort the millionaires' names, ascending by their LAST name. // Create some banks and store in a List List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; // Create some customers and store in a List List <Customer> customers2 = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; var millionaireReport = from customer in customers where customer.Balance >= 1000000 orderby customer.Name descending select customer; Console.WriteLine("Millionaire Names: "); foreach (var customer in millionaireReport) { Console.WriteLine($"{customer.Name} at {customer.Bank}"); } var peopleWithFullBankNames = from bank in banks join customer in customers2 on bank.Symbol equals customer.Bank select new { Bank = bank.Name, Customer = customer.Name }; foreach (var person in peopleWithFullBankNames) { Console.WriteLine($"{person.Customer} banks at {person.Bank}"); } }
private void CreateChildren(MNodeList childList, int listSize) { // Set the parameters for the performance for the different view types of a folder int viewportItemCount, backgroundItemCount; InitializePerformanceParameters(out viewportItemCount, out backgroundItemCount); // We will not add nodes one by one in the dispatcher but in groups List <IMegaNode> helperList; try { helperList = new List <IMegaNode>(1024); } catch (ArgumentOutOfRangeException) { helperList = new List <IMegaNode>(); } for (int i = 0; i < listSize; i++) { // If the task has been cancelled, stop processing if (LoadingCancelToken.IsCancellationRequested) { LoadingCancelToken.ThrowIfCancellationRequested(); } // To avoid pass null values to CreateNew if (childList.get(i) == null) { continue; } var node = NodeService.CreateNew(this.MegaSdk, this.AppInformation, childList.get(i), this.Type, ChildNodes); // If node creation failed for some reason, continue with the rest and leave this one if (node == null) { continue; } // If the user is moving nodes, check if the node had been selected to move // and establish the corresponding display mode if (CurrentDisplayMode == DriveDisplayMode.CopyOrMoveItem) { // Check if it is the only focused node if ((FocusedNode != null) && (node.OriginalMNode.getBase64Handle() == FocusedNode.OriginalMNode.getBase64Handle())) { node.DisplayMode = NodeDisplayMode.SelectedForCopyOrMove; FocusedNode = node; } // Check if it is one of the multiple selected nodes IsSelectedNode(node); } helperList.Add(node); // First add the viewport items to show some data to the user will still loading if (i == viewportItemCount) { var waitHandleViewportNodes = new AutoResetEvent(false); Deployment.Current.Dispatcher.BeginInvoke(() => { // If the task has been cancelled, stop processing foreach (var megaNode in helperList.TakeWhile(megaNode => !LoadingCancelToken.IsCancellationRequested)) { ChildNodes.Add(megaNode); } waitHandleViewportNodes.Set(); }); waitHandleViewportNodes.WaitOne(); helperList.Clear(); continue; } if (helperList.Count != backgroundItemCount || i <= viewportItemCount) { continue; } // Add the rest of the items in the background to the list var waitHandleBackgroundNodes = new AutoResetEvent(false); Deployment.Current.Dispatcher.BeginInvoke(() => { // If the task has been cancelled, stop processing foreach (var megaNode in helperList.TakeWhile(megaNode => !LoadingCancelToken.IsCancellationRequested)) { ChildNodes.Add(megaNode); } waitHandleBackgroundNodes.Set(); }); waitHandleBackgroundNodes.WaitOne(); helperList.Clear(); } // Add any nodes that are left over var waitHandleRestNodes = new AutoResetEvent(false); Deployment.Current.Dispatcher.BeginInvoke(() => { // Show the user that processing the childnodes is done SetProgressIndication(false); // Set empty content to folder instead of loading view SetEmptyContentTemplate(false); // If the task has been cancelled, stop processing foreach (var megaNode in helperList.TakeWhile(megaNode => !LoadingCancelToken.IsCancellationRequested)) { ChildNodes.Add(megaNode); } waitHandleRestNodes.Set(); }); waitHandleRestNodes.WaitOne(); OnUiThread(() => OnPropertyChanged("HasChildNodesBinding")); }
public virtual string Compile(ref string props, ref bool hidePants, ref bool hideHair) { var compiled = String.Empty; if (_Items == null || _Items.Count == 0) { return(compiled); } _Items.SortLayers(); var noHue = FixHue(0); var noText = Parent.Intern(" "); foreach (var item in _Items.TakeWhile(i => i.Layer.IsOrdered()) .Where(i => !_Body.IsGhost || i.ItemID == 8270 || i.ItemID == 8271)) { if (item.ItemID == 0x1411 || item.ItemID == 0x141A) // plate legs { hidePants = true; } else if (hidePants && item.Layer == Layer.Pants) { continue; } if (!hideHair && (item.ItemID == 8270 || item.ItemID == 8271 || item.Layer == Layer.Helm)) { hideHair = true; } var gump = item.GetGumpID(_Body.IsFemale); if (gump <= 0) { continue; } var hue = _SolidHue >= 0 ? _SolidHue : item.Hue; if (hue > 0 || (_SolidHue >= 0 && hue == _SolidHue)) { compiled += String.Format(_Format1B, _X, _Y, gump, FixHue(hue)); } else { compiled += String.Format(_Format1A, _X, _Y, gump); } if (_Properties) { var tooltip = String.Format(_Format5, item.Serial.Value); foreach (var b in item.GetGumpBounds()) { props += String.Format(_Format4, _X + b.X, _Y + b.Y, b.Width, b.Height, noHue, noText); props += tooltip; } } } return(compiled); }
static void Main(string[] args) { var films = new List <Film> { new Film { Name = "Jaws", Year = 1975 }, new Film { Name = "Singing in the Rain", Year = 1952 }, new Film { Name = "Some like it Hot", Year = 1959 }, new Film { Name = "The Wizard of Oz", Year = 1939 }, new Film { Name = "It’s a Wonderful Life", Year = 1946 }, new Film { Name = "American Beauty", Year = 1999 }, new Film { Name = "High Fidelity", Year = 2000 }, new Film { Name = "The Usual Suspects", Year = 1995 } }; //Создание многократно используемого делегата для вывода списка на консоль Action <Film> print = film => Console.WriteLine($"Name={film.Name}, Year={film.Year}"); //Вывод на консоль исходного списка films.ForEach(print); //Создание и вывод отфильтрованного списка films.FindAll(film => film.Year < 1960).ForEach(print); //Сортировка исходного списка films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name)); //or films.OrderBy(film => film.Name); { // OrderByDescending, Skip, SkipWhile, Take, TakeWhile, Select, Concat int[] n = { 1, 3, 5, 6, 3, 6, 7, 8, 45, 3, 7, 6 }; IEnumerable <int> res; res = n.OrderByDescending(g => g).Skip(3); res = n.OrderByDescending(g => g).Take(3); res = n.Select(g => g * 2); // to delete from array number 45 res = n.TakeWhile(g => g != 45).Concat(n.SkipWhile(s => s != 45).Skip(1)); } { //Дана последовательность непустых строк. //Объединить все строки в одну. List <string> str = new List <string> { "1qwerty", "cqwertyc", "cqwe", "c" }; string amount = str.Aggregate <string>((x, y) => x + y); } { //LinqBegin3. Дано целое число L (> 0) и строковая последовательность A. //Вывести последнюю строку из A, начинающуюся с цифры и имеющую длину L. //Если требуемых строк в последовательности A нет, то вывести строку «Not found». //Указание.Для обработки ситуации, связанной с отсутствием требуемых строк, использовать операцию ??. int length = 8; List <string> str = new List <string> { "1qwerty", "2qwerty", "7qwe" }; string res = str.FirstOrDefault(x => (Char.IsDigit(x[0])) && (x.Length == length)) ?? "Not found"; } { //LinqBegin5. Дан символ С и строковая последовательность A. //Найти количество элементов A, которые содержат более одного символа и при этом начинаются и оканчиваются символом C. char c = 'c'; List <string> str = new List <string> { "1qwerty", "cqwertyc", "cqwe", "c" }; int amount = str.Count(x => (x.StartsWith(c.ToString())) && (x.EndsWith(c.ToString())) && (x.Length > 1)); } { //LinqBegin6. Дана строковая последовательность. //Найти сумму длин всех строк, входящих в данную последовательность. //TODO string substr = "qwe"; List <string> str = new List <string> { "1qwerty", "cqowertyc", "cqwe", "c" }; int amount = str.FindAll(x => (x.Contains(substr))).Sum(x => x.Length); } { //LinqBegin11. Дана последовательность непустых строк. //Пполучить строку, состоящую из начальных символов всех строк исходной последовательности. //TODO List <string> str = new List <string> { "1qwerty", "owertyc", "qwe", "c" }; string firstSymbols = str.Aggregate((x, y) => x[0].ToString() + y[0].ToString()); } { //LinqBegin30. Дано целое число K (> 0) и целочисленная последовательность A. //Найти теоретико-множественную разность двух фрагментов A: первый содержит все четные числа, //а второй — все числа с порядковыми номерами, большими K. //В полученной последовательности(не содержащей одинаковых элементов) поменять порядок элементов на обратный. int k = 5; IEnumerable <int> n = new int[] { 12, 88, 1, 3, 5, 4, 6, 6, 2, 5, 8, 9, 0, 90 }; var res = n.Where(x => x % 2 == 0).Except(n.Skip(k)).Reverse(); } { //LinqBegin22. Дано целое число K (> 0) и строковая последовательность A. //Строки последовательности содержат только цифры и заглавные буквы латинского алфавита. //Извлечь из A все строки длины K, оканчивающиеся цифрой, отсортировав их по возрастанию. //TODO int k = 5; List <string> a = new List <string> { "ASD123432", "1AS22", "AA23A", "22111", "8UIO9" }; var result = a.Where(x => x.Length == k && Char.IsDigit(x[k - 1])).OrderBy(x => x); } { //LinqBegin29. Даны целые числа D и K (K > 0) и целочисленная последовательность A. //Найти теоретико - множественное объединение двух фрагментов A: первый содержит все элементы до первого элемента, //большего D(не включая его), а второй — все элементы, начиная с элемента с порядковым номером K. //Полученную последовательность(не содержащую одинаковых элементов) отсортировать по убыванию. //TODO int d = 6; int k = 3; var a = new List <int> { 1, 5, 6, 7, -4, -1, 0, 2, -6 }; var res = a.TakeWhile(x => x <= d).Union(a.Skip(k - 1)).Distinct().OrderByDescending(x => x); } { //LinqBegin34. Дана последовательность положительных целых чисел. //Обрабатывая только нечетные числа, получить последовательность их строковых представлений и отсортировать ее по возрастанию. IEnumerable <int> n = new int[] { 12, 88, 1, 3, 5, 4, 6, 6, 2, 5, 8, 9, 0, 90 }; var res = n.Where(x => x % 2 != 0).Select(x => x.ToString()).OrderBy(x => x); } { //LinqBegin36. Дана последовательность непустых строк. //Получить последовательность символов, которая определяется следующим образом: //если соответствующая строка исходной последовательности имеет нечетную длину, то в качестве //символа берется первый символ этой строки; в противном случае берется последний символ строки. //Отсортировать полученные символы по убыванию их кодов. //TODO IEnumerable <string> n = new List <string> { "asdawdwawdaw", "aisofdi3498gfhasugsj", "adq3wo89ahud", "asda2", "123asd", "h" }; var res = n.Select(x => x.Length % 2 != 0 ? x[0] : x[x.Length - 1]).OrderByDescending(x => x); } { //LinqBegin44. Даны целые числа K1 и K2 и целочисленные последовательности A и B. //Получить последовательность, содержащую все числа из A, большие K1, и все числа из B, меньшие K2. //Отсортировать полученную последовательность по возрастанию. //TODO int k1 = 5; int k2 = 10; var a = new List <int> { 2, 6, 7, 8, 4, 2 }; var b = new List <int> { 34, 7, 9, 6, 3, 66, 2 }; var result = a.Where(x => x > k1).Union(b.Where(x => x < k2)).OrderBy(X => X); } { //LinqBegin46. Даны последовательности положительных целых чисел A и B; все числа в каждой последовательности различны. //Найти последовательность всех пар чисел, удовлетворяющих следующим условиям: первый элемент пары принадлежит //последовательности A, второй принадлежит B, и оба элемента оканчиваются одной и той же цифрой. //Результирующая последовательность называется внутренним объединением последовательностей A и B по ключу, //определяемому последними цифрами исходных чисел. //Представить найденное объединение в виде последовательности строк, содержащих первый и второй элементы пары, //разделенные дефисом, например, «49 - 129». IEnumerable <int> n1 = new int[] { 12, 88, 11, 3, 55, 679, 222, 845, 9245 }; IEnumerable <int> n2 = new int[] { 123, 888, 551, 443, 69, 222, 780 }; var res = n1.Join(n2, x => x % 10, y => y % 10, (x, y) => x.ToString() + " - " + y.ToString()); } { //LinqBegin48.Даны строковые последовательности A и B; все строки в каждой последовательности различны, //имеют ненулевую длину и содержат только цифры и заглавные буквы латинского алфавита. //Найти внутреннее объединение A и B, каждая пара которого должна содержать строки одинаковой длины. //Представить найденное объединение в виде последовательности строк, содержащих первый и второй элементы пары, //разделенные двоеточием, например, «AB: CD». Порядок следования пар должен определяться порядком //первых элементов пар(по возрастанию), а для равных первых элементов — порядком вторых элементов пар(по убыванию). //TODO var a = new List <string> { "ASL12", "A4HU", "KLJ21", "LKJSA", "12312" }; var b = new List <string> { "ASD220", "8897H", "DKASFJD9", "2J2JK", "997HH" }; var res = a.Join(b, x => x.Length, y => y.Length, (x, y) => x + ": " + y) .OrderBy(x => x.Split(new char[] { ':' }, 1)) .ThenBy(x => x.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]); } { //LinqBegin56. Дана целочисленная последовательность A. //Сгруппировать элементы последовательности A, оканчивающиеся одной и той же цифрой, и на основе этой группировки //получить последовательность строк вида «D: S», где D — ключ группировки (т.е.некоторая цифра, которой оканчивается //хотя бы одно из чисел последовательности A), а S — сумма всех чисел из A, которые оканчиваются цифрой D. //Полученную последовательность упорядочить по возрастанию ключей. //Указание.Использовать метод GroupBy. IEnumerable <int> n = new int[] { 12, 88, 11, 3, 55, 679, 222, 845, 9245 }; List <string> res = new List <string>(); IEnumerable <IGrouping <int, int> > groups = n.GroupBy(x => x % 10).OrderBy(x => x.Key); foreach (IGrouping <int, int> group in groups) { string listElement = group.Key.ToString(); int summaryValue = 0; foreach (int item in group) { summaryValue += item; } listElement = listElement + ": " + summaryValue.ToString(); res.Add(listElement); } { //LinqObj17. Исходная последовательность содержит сведения об абитуриентах. Каждый элемент последовательности //включает следующие поля: < Номер школы > < Год поступления > < Фамилия > //Для каждого года, присутствующего в исходных данных, вывести число различных школ, которые окончили абитуриенты, //поступившие в этом году (вначале указывать число школ, затем год). //Сведения о каждом годе выводить на новой строке и упорядочивать по возрастанию числа школ, //а для совпадающих чисел — по возрастанию номера года. //TODO var student1 = new Student { School = 9, Year = 1999, Surname = "Pupkin" }; var student2 = new Student { School = 4, Year = 1998, Surname = "Petrov" }; var student3 = new Student { School = 3, Year = 1999, Surname = "Ivanov" }; var student4 = new Student { School = 4, Year = 1998, Surname = "Sidorov" }; var student5 = new Student { School = 5, Year = 1999, Surname = "Mironov" }; var student6 = new Student { School = 4, Year = 1997, Surname = "Nikonov" }; var student7 = new Student { School = 7, Year = 1998, Surname = "Kulikov" }; var student8 = new Student { School = 4, Year = 1999, Surname = "Menshikov" }; var student9 = new Student { School = 9, Year = 1997, Surname = "Bliadze" }; var student10 = new Student { School = 3, Year = 1999, Surname = "Andrijash" }; var students = new Student[] { student1, student2, student3, student4, student5, student6, student7, student8, student9, student10 }; var groups = students.GroupBy(x => x.Year); var res = groups.Select(x => new { SchoolCount = x.Distinct().Count(), Year = x.Key }).OrderBy(x => x.SchoolCount).ThenBy(x => x.Year); foreach (var pair in res) { Console.WriteLine($"{pair.SchoolCount} - {pair.Year}"); } } } }
static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = fruits.Where(fruit => fruit.StartsWith("L")); foreach (string fruit in LFruits) { Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0); foreach (int number in fourSixMultiples) { Console.WriteLine(number); } // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List <string> descend = names.OrderByDescending(a => a).ToList(); foreach (string item in descend) { Console.WriteLine(item); } // Build a collection of these numbers sorted in ascending order List <int> numbers2 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List <int> ascend = numbers2.OrderBy(x => x).ToList(); foreach (int item in ascend) { Console.WriteLine(item); } // Output how many numbers are in this list List <int> numbers3 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine(numbers.Count()); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double moneyMade = purchases.Sum(); Console.WriteLine(moneyMade); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double mostExpenseive = prices.Max(); Console.WriteLine(mostExpenseive); /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; List <int> nonSquares = wheresSquaredo.TakeWhile(n => Math.Sqrt(n) % 1 != 0).ToList(); foreach (var item in nonSquares) { Console.WriteLine(item.ToString()); } List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq */ var groupedByBank = customers.Where(c => c.Balance >= 1000000).GroupBy( p => p.Bank, // Group banks p => p.Name, // by millionaire names (bank, millionaires) => new GroupedMillionaires() { Bank = bank, Millionaires = millionaires } ).ToList(); foreach (var item in groupedByBank) { Console.WriteLine($"{item.Bank}: {string.Join(" and ", item.Millionaires)}"); } // Create some banks and store in a List List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; List <Customer> millionaireReport = customers.Where(c => c.Balance >= 1000000) .Select(c => new Customer() { Name = c.Name, Bank = banks.Find(b => b.Symbol == c.Bank).Name, Balance = c.Balance }) .ToList(); foreach (Customer customer in millionaireReport) { Console.WriteLine($"{customer.Name} at {customer.Bank}"); } }
static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from fruit in fruits where fruit.StartsWith("L") select fruit; foreach (string fruit in LFruits) { Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0).OrderBy(number => number); foreach (var item in fourSixMultiples) { Console.WriteLine(item); } // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List <string> descend = names.OrderByDescending(name => name).ToList(); foreach (var item in descend) { Console.WriteLine(item); } // Build a collection of these numbers sorted in ascending order List <int> unsortedNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List <int> sortedNumbers = unsortedNumbers.OrderBy(number => number).ToList(); foreach (var item in sortedNumbers) { Console.WriteLine(item); } // Output how many numbers are in this list List <int> numbersList = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"There are {numbersList.Count} numbers in numbersList"); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; Console.WriteLine($"The sum of purchases is " + string.Format("{0:0.00}", purchases.Sum())); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; Console.WriteLine($"The highest price in prices is {prices.Max()}"); List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; /* * Store each number in the following List until a perfect square * is detected. * * Expected output is { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46 } * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ IEnumerable <int> notSquares = wheresSquaredo.TakeWhile(number => Math.Sqrt(number) % 1 != 0); foreach (var item in notSquares) { Console.WriteLine($"{item} is not a perfect square"); } }
public static void UpdateDropDownFields(ComboBox cbxDepartments, ComboBox cbxSections, ComboBox cbxCompany, ComboBox cbxCadre, ComboBox cbxCrew) { if (cbxDepartments != null) { List <string> ccftDepartments = (from pds in EFERTDbUtility.mCCFTCentral.PersonalDataStrings where pds != null && pds.PersonalDataFieldID == 5043 && pds.Value != null select pds.Value).Distinct().ToList(); List <string> departments = (from depart in EFERTDbUtility.mEFERTDb.Departments where depart != null && !string.IsNullOrEmpty(depart.DepartmentName) select depart.DepartmentName).ToList(); departments.Insert(0, string.Empty); departments = departments.TakeWhile(a => !ccftDepartments.Exists(b => b.ToLower() == a.ToLower())).ToList(); ccftDepartments.AddRange(departments); ccftDepartments.Sort(); cbxDepartments.Items.AddRange(ccftDepartments.ToArray()); } if (cbxSections != null) { List <string> ccftSections = (from pds in EFERTDbUtility.mCCFTCentral.PersonalDataStrings where pds != null && pds.PersonalDataFieldID == 12951 && pds.Value != null select pds.Value).Distinct().ToList(); List <string> sections = (from section in EFERTDbUtility.mEFERTDb.Sections where section != null && !string.IsNullOrEmpty(section.SectionName) select section.SectionName).ToList(); sections.Insert(0, string.Empty); sections = sections.TakeWhile(a => !ccftSections.Exists(b => b.ToLower() == a.ToLower())).ToList(); ccftSections.AddRange(sections); ccftSections.Sort(); cbxSections.Items.AddRange(ccftSections.ToArray()); } if (cbxCompany != null) { List <string> ccftCompanyNames = (from pds in EFERTDbUtility.mCCFTCentral.PersonalDataStrings where pds != null && pds.PersonalDataFieldID == 5059 && pds.Value != null select pds.Value).Distinct().ToList(); List <string> companies = (from company in EFERTDbUtility.mEFERTDb.Companies where company != null && !string.IsNullOrEmpty(company.CompanyName) select company.CompanyName).ToList(); companies.Insert(0, string.Empty); companies = companies.TakeWhile(a => !ccftCompanyNames.Exists(b => b.ToLower() == a.ToLower())).ToList(); ccftCompanyNames.AddRange(companies); ccftCompanyNames.Sort(); cbxCompany.Items.AddRange(ccftCompanyNames.ToArray()); } if (cbxCadre != null) { List <string> ccftCadres = (from pds in EFERTDbUtility.mCCFTCentral.PersonalDataStrings where pds != null && pds.PersonalDataFieldID == 12952 && pds.Value != null select pds.Value).Distinct().ToList(); List <string> cadres = (from cadre in EFERTDbUtility.mEFERTDb.Cadres where cadre != null && !string.IsNullOrEmpty(cadre.CadreName) select cadre.CadreName).ToList(); cadres.Insert(0, string.Empty); cadres = cadres.TakeWhile(a => !ccftCadres.Exists(b => b.ToLower() == a.ToLower())).ToList(); ccftCadres.AddRange(cadres); ccftCadres.Sort(); cbxCadre.Items.AddRange(ccftCadres.ToArray()); } if (cbxCrew != null) { List <string> crews = (from pds in EFERTDbUtility.mCCFTCentral.PersonalDataStrings where pds != null && pds.PersonalDataFieldID == 12869 && pds.Value != null select pds.Value).Distinct().ToList(); crews.Insert(0, string.Empty); crews.Sort(); cbxCrew.Items.AddRange(crews.ToArray()); } }
public static void AddJob(SingleRunJob job) { var i = JobList.TakeWhile(oldJob => job.Priority >= oldJob.Priority).Count(); JobList.Insert(i, job); }
static void Main(string[] args) { Console.WriteLine("Just some linq-ed up stuff"); List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from fruit in fruits where fruit.StartsWith('L') select fruit; // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(n => n % 4 == 0 || n % 6 == 0); // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List <string> descend = (from name in names orderby name descending select name).ToList(); IEnumerable <string> descend2 = names.OrderByDescending(name => name); // Build a collection of these numbers sorted in ascending order List <int> numberList = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> numberListAscending = numberList.OrderByDescending(num => num); //----------------------------- // // Output how many numbers are in this list List <int> howmanyNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"Howmany Nums {howmanyNumbers.Count}"); // How much money have we made? //m stands for decimal List <decimal> purchases = new List <decimal> { 2340.29m, 745.31m, 21.76m, 34.03m, 4786.45m, 879.45m, 9442.85m, 2454.63m, 45.65m }; Console.WriteLine($"All the Money {purchases.Sum()}"); // decimal sum = (from x in purchases select x).Sum(); //for each multiply by 100 to remove decimal then add together(sum) then //divide by 100 List <double> purchases2 = new List <double> { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; IEnumerable <double> allNumbs = from count in purchases2 select count * 100; var allMoneyAgain = Math.Round(allNumbs.Sum() * .01, 2); List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; Console.WriteLine($"Max Value is {prices.Max()}"); List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; /* * Store each number in the following List until a perfect square * is detected. * * Expected output is { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46 } * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ //first write out to determine is sqrRoot double testVal = 66; if (testVal == 0 || testVal == 1) { Console.WriteLine($"The Test Val {testVal} one or zero so no go"); } else { // Find floating point value of // square root of x. double sr = Math.Sqrt(testVal); // If square root is an integer if ((sr - Math.Floor(sr)) == 0) { Console.WriteLine($"The Test Val {testVal} yeah"); } else { Console.WriteLine($"The Test Val {testVal} NOPE"); } } var notSQList = wheresSquaredo.TakeWhile(item => { var sr = Math.Sqrt(item); return((sr - Math.Floor(sr)) != 0); }); foreach (double num in notSQList) { Console.WriteLine(num); } string[] fruits2 = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; IEnumerable <string> query = fruits2.TakeWhile(fruit => { return(String.Compare("orange", fruit, true) != 0); }); foreach (string fruit in query) { Console.WriteLine(fruit); } }
/// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> public void Solve(Matrix matrix, Vector input, Vector result) { // If we were stopped before, we are no longer // We're doing this at the start of the method to ensure // that we can use these fields immediately. _hasBeenStopped = false; _currentSolver = null; // Error checks if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (input == null) { throw new ArgumentNullException("input"); } if (result == null) { throw new ArgumentNullException("result"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } // Initialize the solver fields // Set the convergence monitor if (_iterator == null) { _iterator = Iterator.CreateDefault(); } // Load the solvers into our own internal data structure // Once we have solvers we can always reuse them. if (_solvers.Count == 0) { LoadSolvers(); } // Create a copy of the solution and result vectors so we can use them // later on var internalInput = (Vector)input.Clone(); var internalResult = (Vector)result.Clone(); foreach (var solver in _solvers.TakeWhile(solver => !_hasBeenStopped)) { // Store a reference to the solver so we can stop it. _currentSolver = solver; try { // Reset the iterator and pass it to the solver _iterator.ResetToPrecalculationState(); solver.SetIterator(_iterator); // Start the solver solver.Solve(matrix, internalInput, internalResult); } catch (Exception) { // The solver broke down. // Log a message about this // Switch to the next preconditioner. // Reset the solution vector to the previous solution input.CopyTo(internalInput); _status = RunningStatus; continue; } // There was no fatal breakdown so check the status if (_iterator.Status is CalculationConverged) { // We're done internalResult.CopyTo(result); break; } // We're not done // Either: // - calculation finished without convergence if (_iterator.Status is CalculationStoppedWithoutConvergence) { // Copy the internal result to the result vector and // continue with the calculation. internalResult.CopyTo(result); } else { // - calculation failed --> restart with the original vector // - calculation diverged --> restart with the original vector // - Some unknown status occurred --> To be safe restart. input.CopyTo(internalInput); } } // Inside the loop we already copied the final results (if there are any) // So no need to do that again. // Clean up // No longer need the current solver _currentSolver = null; // Set the final status _status = _iterator.Status; }
private async void Button_Click(object sender, RoutedEventArgs e) { this.IsEnabled = false; //this.InvalidateVisual(); // Give the window a chance to redraw await Task.Delay(TimeSpan.FromMilliseconds(1)); try { var allCards = JsonConvert.DeserializeObject <Dictionary <string, Card> >(File.ReadAllText("AllCards.json", Encoding.UTF8)).Values.ToList(); var additionalCards = new List <Card>(); // Split, double faced and flip cards are represented as a separate left and right half in the source data foreach (var leftHalf in allCards.Where(p => p.Layout == "split" && p.Names.FirstOrDefault() == p.Name)) { var rightHalfName = leftHalf.Names.LastOrDefault(); var rightHalf = allCards.Single(p => p.Name == rightHalfName); var splitCard = new Card { Name = leftHalf.Name + " // " + rightHalf.Name, ManaCost = leftHalf.ManaCost + "//" + rightHalf.ManaCost, Type = leftHalf.Type + "//" + rightHalf.Type, Text = leftHalf.Text + "\n // " + rightHalf.Text }; additionalCards.Add(splitCard); } foreach (var leftHalf in allCards.Where(p => p.Layout == "double-faced" && p.Names.FirstOrDefault() == p.Name)) { var rightHalfName = leftHalf.Names.LastOrDefault(); var rightHalf = allCards.Single(p => p.Name == rightHalfName); leftHalf.Name = leftHalf.Name; leftHalf.ManaCost = leftHalf.ManaCost; leftHalf.Type = leftHalf.Type; leftHalf.Text = "Transforms into " + rightHalf.Name + " [" + rightHalf.Type + ", " + rightHalf.Power + "/" + rightHalf.Toughness + "]; " + leftHalf.Text + "\n // " + (rightHalf.Text != null ? rightHalf.Text.Replace(rightHalf.Name, "~") : ""); } foreach (var leftHalf in allCards.Where(p => p.Layout == "flip" && p.Names.FirstOrDefault() == p.Name)) { var rightHalfName = leftHalf.Names.LastOrDefault(); var rightHalf = allCards.Single(p => p.Name == rightHalfName); leftHalf.Name = leftHalf.Name; leftHalf.ManaCost = leftHalf.ManaCost; leftHalf.Type = leftHalf.Type; leftHalf.Text = "Flips to " + rightHalf.Name + " [" + rightHalf.Type + (rightHalf.Power != null ? ", " + rightHalf.Power + "/" + rightHalf.Toughness : "") + "]; " + leftHalf.Text + "\n // " + (rightHalf.Text != null ? rightHalf.Text.Replace(rightHalf.Name, "~") : ""); } allCards.AddRange(additionalCards); // Parse the deck strings and shorten the text of cards that are included in one or more decks var shortener = new CardTextShortener(); var decks = new List <List <Card> >(); var sideboards = new List <List <Card> >(); for (int deckNumber = 0; deckNumber < this.deckInputs.Count; deckNumber++) { if (this.deckInputs[deckNumber].Text.Trim().Length == 0) { continue; } var deck = ParseDeckString(this.deckInputs[deckNumber].Text, allCards); var sideboard = ParseDeckString(this.sideboardInputs[deckNumber].Text, allCards); foreach (var card in deck.Concat(sideboard)) { shortener.ProcessCard(card, this.grayscaleSymbols.IsChecked == true, this.omitTypeLineForBasics.IsChecked == true); } decks.Add(deck); sideboards.Add(sideboard); } // Validate sizes of the decks if (decks.Any(p => p.Count != decks[0].Count)) { var numberOfValidDecks = decks.TakeWhile(p => p.Count == decks[0].Count).Count(); var invalidDeck = decks.First(p => p.Count != decks[0].Count); throw new ApplicationException("All decks must contain the same number of cards (deck 1 contains " + decks[0].Count + " cards, deck " + (numberOfValidDecks + 1) + " contains " + invalidDeck.Count + " cards.)"); } // Validate sizes of the sideboards if (sideboards.Any(p => p.Count != sideboards[0].Count)) { var numberOfValidDecks = sideboards.TakeWhile(p => p.Count == sideboards[0].Count).Count(); var invalidDeck = sideboards.First(p => p.Count != sideboards[0].Count); throw new ApplicationException("All sideboards must contain the same number of cards (sideboard 1 contains " + sideboards[0].Count + " cards, sideboard " + (numberOfValidDecks + 1) + " contains " + invalidDeck.Count + " cards.)"); } // Format the decks into HTML var arranger = new SimpleArranger(); decks = arranger.ArrangeCards(decks); sideboards = arranger.ArrangeCards(sideboards); string str = @" <html> <head> <meta charset=""utf-8""> <style> .card { table-layout: fixed; display:inline-block; text-overflow:ellipsis; } .card > div { width: 57mm; height: 83mm; border: 1px black solid;"; if (this.cardSpacing.IsChecked == true) { str += @"margin: 0.5mm;"; } str += @"} .card table { width: 100%; height: 100%; font-size: 3mm; /*11px;*/ padding: 0; border-spacing: 0; }"; if (this.colorCode.IsChecked == true) { str += @"tr.card1 td{ border-left: 4px #B2F1BA solid; } tr.card2 td{ border-left: 4px #C3B5EB solid; } tr.card3 td{ border-left: 4px #FFF4BC solid; } tr.card4 td{ border-left: 4px #FFBFBC solid; } tr.card5 td{ border-left: 4px #83EBE4 solid; }"; } str += @".card td { padding: 1px 1px 1px 1mm; } div.sideboard table { border-top: 3px black dashed; } .cardNameRow { height: 3.5mm; white-space:nowrap; } .deckNumber { float:left; margin-right: 1mm; /*border-radius: 50%; width: 10px; height: 10px; padding: 1px; background: #fff; border: 2px solid #666; color: #666; text-align: center;*/ } .cardName { float:left; font-weight: bold; font-size: 1.1em; } .manaCost { float:right; } .cardSeparator { height:1px; font-size: 1px; padding: 0; } .cardSeparator hr{ border: 0; border-top: 1px black solid; background: none; } .cardTypeRow { height: 3.5mm; /*white-space:nowrap;*/ } .cardType { float:left; } .powerToughness { float:right; } </style> </head> <body> "; var deckSize = decks.Max(p => p.Count); var totalSize = deckSize + sideboards.Max(p => p.Count); for (var i = 0; i < totalSize; i++) { str += @"<div class=""card " + (i >= deckSize ? "sideboard" : "") + @"""> <div> <table>"; for (int j = 0; j < decks.Count; j++) { var deck = decks[j].Concat(sideboards[j]).ToList(); if (deck.Count > i) { var card = deck[i]; if (j > 0) { str += @" <tr class=""cardSeparator card" + (j + 1) + @"""> <td><hr /></td> </tr>"; } str += @"<tr class=""cardNameRow card" + (j + 1) + @"""> <td> " + (this.deckNumbers.IsChecked == true ? @"<span class=""deckNumber"">" + (j + 1) + @"</span> " : "") + @" <span class=""cardName"">" + card.Name + @"</span> <span class=""manaCost"">" + (card.ManaCost ?? "") + @"</span> </td> </tr>"; if (!(this.omitTypeLineForBasics.IsChecked == true && card.Type.Contains("Basic"))) { str += @"<tr class=""cardTypeRow card" + (j + 1) + @"""> <td><span class=""cardType"">" + card.Type + @"</span> <span class=""powerToughness"">" + (card.Power != null ? card.Power + "/" + card.Toughness : (card.Loyalty ?? "")) + @"</span></td> </tr>"; } /*if (card.Text != null) * {*/ str += @"<tr class=""cardText card" + (j + 1) + @"""> <td>" + card.Text + @"</td> </tr>"; /*}*/ } else { str += @"<tr class=""cardNameRow""> <td>-</td> </tr>"; } } str += @" <!--<tr></tr>--> </table> </div> </div>"; } File.WriteAllText("cards.html", str, new UTF8Encoding(true)); if (MessageBox.Show("File generated. Do you wish to open it?" + Environment.NewLine + Environment.NewLine + "WARNING: Internet Explorer does not display the cards correctly. Google Chrome is recommended to print the cards.", "Finished", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { Process.Start("cards.html"); } } catch (ApplicationException ex) { MessageBox.Show("Error: " + ex.Message); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } this.IsEnabled = true; }
public static IEnumerable<long> Primes(long count) { var memoized = new List<long>(); long sqrt = 1; var primes = PotentialPrimes().Where(x => { sqrt = GetSqrtCeiling(x, sqrt); return !memoized .TakeWhile(y => y <= sqrt) .Any(y => x % y == 0); }); var current = 1; foreach (long prime in primes) { //Get x number prime if (current == count) { Debug.WriteLine(prime); yield return prime; break; } current++; //end get x number prime yield return prime; memoized.Add(prime); } }
List<IMessage> TruncateMessages(List<IMessage> msgs) { // we remove msg to recents because their is no time synchronisation between azure VMs DateTime dateLimit = DateTime.Now - limitDateDiff; return msgs.TakeWhile(m => m.Date < dateLimit).ToList(); // TODO : improve performance }
// // Pull off messages from the Queue, batch them up and send them all across // private void ElasticsearchSender() { // Force an inital flush DateTime lastFlushTime = DateTime.MinValue; LogManager.GetCurrentClassLogger() .Info("{0}: Elasticsarch Output To {1} Ready", Thread.CurrentThread.ManagedThreadId, string.Join(",", _hosts)); using (var syncHandle = new ManualResetEventSlim()) { // Execute the query while (!Stop) { if (!CancelToken.IsCancellationRequested) { try { int messageCount = 0; List<JObject> messages = new List<JObject>(); // Lets get whats in the queue lock (_locker) { messageCount = _jsonQueue.Count; // Time to flush? if (messageCount >= _flushSize || (DateTime.UtcNow - lastFlushTime).Seconds >= _idleFlushTimeSeconds) { messages = _jsonQueue.Take(messageCount).ToList(); _jsonQueue.RemoveRange(0, messageCount); if (messages.Count > 0) _manager.IncrementMessageCount(messages.Count); } } // We have some messages to work with if (messages.Count > 0) { var client = getClient(); LogManager.GetCurrentClassLogger() .Debug("Sending {0} Messages to {1}", messages.Count, string.Join(",", _hosts)); // This loop will process all messages we've taken from the queue // that have the same index and type (an elasticsearch requirement) do { try { // Grab all messages with same index and type (this is the whole point, group the same ones) var bulkTypeName = this._parameters.GetTypeName(messages[0]); var bulkIndexName = this._parameters.GetIndexName(messages[0]); IEnumerable<JObject> bulkItems = messages.TakeWhile( message => String.Compare(bulkTypeName, _parameters.GetTypeName(message), false) == 0 && String.Compare(bulkIndexName, _parameters.GetIndexName(message), false) == 0); // Send the message(s), if the are successfully sent, they // are removed from the queue lastFlushTime = transmitBulkData(bulkItems, bulkIndexName, bulkTypeName, client, lastFlushTime, messages); GC.Collect(); } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex); break; } } while (messages.Count > 0); } GC.Collect(); if (!Stop) { syncHandle.Wait(TimeSpan.FromMilliseconds(_interval), CancelToken); } } catch (OperationCanceledException) { break; } catch (Exception ex) { LogManager.GetCurrentClassLogger().Error(ex); } } } } LogManager.GetCurrentClassLogger() .Info("{0}: Elasticsarch Output To {1} Terminated", Thread.CurrentThread.ManagedThreadId, string.Join(",", _hosts)); }
private List<string> GetEvents(string channel) { Subscribe(channel); var headers = new WebHeaderCollection {{"method", "1"}}; var gameDataRequest = powRequest(2, headers); if (string.IsNullOrWhiteSpace(gameDataRequest)) { Debug.WriteLine("[Bet365] Null string"); return null; } var gameData = gameDataRequest.Split((char) 0x01); var newParse = gameDataRequest.Split('|'); var oldParse = gameData[gameData.Length - 1].Split((char) 0x7c); var gameDateList = new List<string>(100); if (newParse.Length == oldParse.Length) return default(List<string>); if (newParse.Length > oldParse.Length) { gameDateList = newParse.ToList(); var countDeleteElems = gameDateList.TakeWhile(str => !str.Contains("CL")).Count(); gameDateList.RemoveRange(0, countDeleteElems); } else { gameDateList = oldParse.ToList(); var countDeleteElems = gameDateList.TakeWhile(str => !str.Contains("CL")).Count(); gameDateList.RemoveRange(0, countDeleteElems); } if (gameDateList.Count == 0) { Debug.WriteLine("[Bet365]gameDateListNull: " + gameDataRequest); return null; } var initialCL = parameterizeLine(gameDateList[0]); var paramsDic = new Dictionary<string, string>(); if (initialCL != null) { initialCL.TryGetValue("CL", out paramsDic); } else { Debug.WriteLine("[Bet365] InitialCl is null. Data from server: " + gameDataRequest); } /*if (paramsDic == null) { Debug.WriteLine("[Bet365] InitialCl is null. Data from server: " + gameDataRequest); return null; }*/ Debug.WriteLine("[Bet365] InitialCl is good. Data from server: " + gameDataRequest); var events = new List<string>(5); var isTennis = false; var isFirst = true; foreach (var data in gameDateList) { if (isFirst) { isFirst = false; continue; } var lineData = parameterizeLine(data); if (lineData == null) continue; if (!isTennis) { if (!lineData.ContainsKey("CL")) continue; isTennis = true; continue; } if (lineData.ContainsKey("CL")) { break; } if (lineData.ContainsKey("CL")) { break; } if (lineData.ContainsKey("EV")) { var Id = ""; Dictionary<string, string> tmp; lineData.TryGetValue("EV", out tmp); if (tmp != null) tmp.TryGetValue("ID", out Id); else Debug.WriteLine("[Bet365]No id in parseline. Continue"); if (Id == null) Debug.WriteLine("[Bet365] ID IS NULL"); if ((Id != null) && (Id.Trim().Length == 18)) { events.Add(Id.Trim()); } } } Unsubscribe(channel); return events; }
static void Main() { List<int> list = new List<int>() { 1, 2, 3, 4, 6, 11, 3 }; Console.WriteLine(string.Join(", ", list.TakeWhile(x => x < 10))); }
/// <summary> Constructor for a new instance of the Thematic_Headings_AdminViewer class </summary> /// <param name="User"> Authenticated user information </param> /// <param name="Current_Mode"> Mode / navigation information for the current request </param> /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param> /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param> /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param> /// <remarks> Postback from handling an edit or new thematic heading is handled here in the constructor </remarks> public Thematic_Headings_AdminViewer(User_Object User, SobekCM_Navigation_Object Current_Mode, List<Thematic_Heading> Thematic_Headings, Aggregation_Code_Manager Code_Manager, Custom_Tracer Tracer) : base(User) { Tracer.Add_Trace("Thematic_Headings_AdminViewer.Constructor", String.Empty); // Get the current list of thematic headings thematicHeadings = Thematic_Headings; // Save the mode currentMode = Current_Mode; // Set action message to nothing to start actionMessage = String.Empty; // If the user cannot edit this, go back if ((!user.Is_System_Admin) && ( !user.Is_Portal_Admin )) { currentMode.Mode = Display_Mode_Enum.My_Sobek; currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home; currentMode.Redirect(); return; } // Handle any post backs if (currentMode.isPostBack) { try { // Pull the standard values from the form NameValueCollection form = HttpContext.Current.Request.Form; string save_value = form["admin_heading_tosave"]; string action_value = form["admin_heading_action"]; // Switch, depending on the request if (action_value != null) { switch (action_value.Trim().ToLower()) { case "edit": string new_name = form["form_heading_name"]; if (new_name != null) { int id = Convert.ToInt32(save_value); int order = 1 + Thematic_Headings.TakeWhile(ThisHeading => ThisHeading.ThematicHeadingID != id).Count(); if (SobekCM_Database.Edit_Thematic_Heading(id, order, new_name, Tracer) < 1) { actionMessage = "Unable to edit existing thematic heading"; } else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } actionMessage = "Thematic heading edits saved"; } } break; case "delete": int thematicDeleteId = Convert.ToInt32(save_value); if (!SobekCM_Database.Delete_Thematic_Heading(thematicDeleteId, Tracer)) { // Set action message actionMessage = "Unable to delete existing thematic heading"; } else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Remove this thematic heading from the list int i = 0; while (i < Thematic_Headings.Count) { if (Thematic_Headings[i].ThematicHeadingID == thematicDeleteId) Thematic_Headings.RemoveAt(i); else i++; } } // Set action message actionMessage = "Thematic heading deleted"; } break; case "new": int new_order = Thematic_Headings.Count + 1; int newid = SobekCM_Database.Edit_Thematic_Heading(-1, new_order, save_value, Tracer); if ( newid < 1) actionMessage = "Unable to save new thematic heading"; else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } // Add this blank thematic heading to the code manager Code_Manager.Add_Blank_Thematic_Heading(newid); actionMessage = "New thematic heading saved"; } break; case "moveup": string[] moveup_split = save_value.Split(",".ToCharArray()); int moveup_id = Convert.ToInt32(moveup_split[0]); int moveup_order = Convert.ToInt32(moveup_split[1]); if (moveup_order > 1) { Thematic_Heading themeHeading = Thematic_Headings[moveup_order - 1]; if (themeHeading.ThematicHeadingID == moveup_id) { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Move this thematic heading up Thematic_Headings.Remove(themeHeading); Thematic_Headings.Insert(moveup_order - 2, themeHeading); int current_order = 1; foreach (Thematic_Heading thisTheme in Thematic_Headings) { SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer); current_order++; } // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } } } break; case "movedown": string[] movedown_split = save_value.Split(",".ToCharArray()); int movedown_id = Convert.ToInt32(movedown_split[0]); int movedown_order = Convert.ToInt32(movedown_split[1]); if (movedown_order < Thematic_Headings.Count) { Thematic_Heading themeHeading = Thematic_Headings[movedown_order - 1]; if (themeHeading.ThematicHeadingID == movedown_id) { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Move this thematic heading down Thematic_Headings.Remove(themeHeading); Thematic_Headings.Insert(movedown_order, themeHeading); int current_order = 1; foreach (Thematic_Heading thisTheme in Thematic_Headings) { SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer); current_order++; } // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } } } break; } } } catch (Exception) { actionMessage = "Unknown error caught while handling your reqeust"; } } }
Type?GetNextMigrationToRun(IDbConnection db, List <Type> migrationTypes) { var completedMigrations = new List <Type>(); Type?nextRun = null; var q = db.From <Migration>() .OrderByDescending(x => x.Name).Limit(1); var lastRun = db.Single(q); if (lastRun != null) { var elapsedTime = DateTime.UtcNow - lastRun.CreatedDate; if (lastRun.CompletedDate == null) { if (elapsedTime < Timeout) { throw new InfoException($"Migration '{lastRun.Name}' is still in progress, timeout in {(Timeout - elapsedTime).TotalSeconds:N3}s."); } Log.Info($"Migration '{lastRun.Name}' failed to complete {elapsedTime.TotalSeconds:N3}s ago, re-running..."); db.DeleteById <Migration>(lastRun.Id); } // Re-run last migration if (lastRun.CompletedDate == null) { foreach (var migrationType in migrationTypes) { if (migrationType.Name != lastRun.Name) { completedMigrations.Add(migrationType); } else { migrationTypes.RemoveAll(x => completedMigrations.Contains(x)); return(migrationType); } } return(null); } // Remove completed migrations completedMigrations = migrationTypes.Any(x => x.Name == lastRun.Name) ? migrationTypes.TakeWhile(x => x.Name != lastRun.Name).ToList() : new List <Type>(); if (completedMigrations.Count > 0) { migrationTypes.RemoveAll(x => completedMigrations.Contains(x)); } var nextMigration = migrationTypes.FirstOrDefault(); if (nextMigration == null) { return(null); } // Remove completed migration if (nextMigration.Name == lastRun.Name) { migrationTypes.Remove(nextMigration); } } // Return next migration return(migrationTypes.FirstOrDefault()); }
/// <summary> /// Crops data if id found /// </summary> /// <param name="data">List of media data</param> /// <param name="stopatMediaId">The media id without the _user suffix</param> /// <returns>true if id found, false otherwise</returns> private static bool CropDataIfIdFound(List<Models.Media> data, string stopatMediaId) { if (stopatMediaId == null) { return false; } int count = data.Count; data = data.TakeWhile(x => x.Id != stopatMediaId).ToList(); return count != data.Count; }
static void Main(string[] args) { Console.WriteLine("Hello World!"); // Find the words in the collection that start with the letter 'L' List<string> fruits = new List<string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable<string> LFruits = fruits.Where(fruit => fruit.StartsWith("L")); Console.WriteLine("Fruits that start with L: "); foreach (string fruit in LFruits) { Console.Write($"{fruit}, "); } Console.WriteLine(" "); Console.WriteLine(" "); // Which of the following numbers are multiples of 4 or 6 List<int> numbers = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable<int> fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0); Console.WriteLine("Numbers filtered, multiples of 4 or 6: "); foreach (int number in fourSixMultiples) { Console.Write($"{number}, "); } Console.WriteLine(" "); Console.WriteLine(" "); // Order these student names alphabetically, in descending order (Z to A) List<string> names = new List<string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable<string> namesSorted = names.OrderByDescending(a => a); Console.WriteLine("Names sorted in Descending Order: "); foreach (string name in namesSorted) { Console.Write($"{name}, "); } Console.WriteLine(" "); Console.WriteLine(" "); // Build a collection of these numbers sorted in ascending order List<int> numbersForOrdering = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable<int> numbersSorted = numbersForOrdering.OrderBy(n => n); Console.WriteLine("Numbers sorted in Ascending Order: "); foreach (int number in numbersSorted) { Console.Write($"{number} "); } Console.WriteLine(" "); Console.WriteLine(" "); // Output how many numbers are in this list List<int> numbersToAggregate = new List<int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"Count of numbers in list: {numbersToAggregate.Count()}"); Console.WriteLine(" "); Console.WriteLine(" "); // How much money have we made? List<double> purchases = new List<double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; Console.WriteLine($"We have made: ${purchases.Sum()}"); Console.WriteLine(" "); Console.WriteLine(" "); // What is our most expensive product? List<double> prices = new List<double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; IEnumerable<double> sortedPrices = prices.OrderByDescending(n => n); double largestPrice = sortedPrices.First(); Console.WriteLine($"Most expensive product costs ${largestPrice}"); Console.WriteLine(" "); Console.WriteLine(" "); List<int> wheresSquaredo = new List<int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; /* Store each number in the following List until a perfect square is detected. Expected output is { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46 } Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List<int> stopAtSquare = wheresSquaredo.TakeWhile(num => (Math.Sqrt(num) % 1 != 0)).ToList(); Console.WriteLine("Stop at perfect square: "); foreach (int number in stopAtSquare) { Console.Write($"{number}, "); } Console.WriteLine(" "); Console.WriteLine(" "); // Build a collection of customers who are millionaires List<Customer> customers = new List<Customer>() { new Customer(){ Name="Bob Lesman", Balance=80345.66, Bank="FTB"}, new Customer(){ Name="Joe Landy", Balance=9284756.21, Bank="WF"}, new Customer(){ Name="Meg Ford", Balance=487233.01, Bank="BOA"}, new Customer(){ Name="Peg Vale", Balance=7001449.92, Bank="BOA"}, new Customer(){ Name="Mike Johnson", Balance=790872.12, Bank="WF"}, new Customer(){ Name="Les Paul", Balance=8374892.54, Bank="WF"}, new Customer(){ Name="Sid Crosby", Balance=957436.39, Bank="FTB"}, new Customer(){ Name="Sarah Ng", Balance=56562389.85, Bank="FTB"}, new Customer(){ Name="Tina Fey", Balance=1000000.00, Bank="CITI"}, new Customer(){ Name="Sid Brown", Balance=49582.68, Bank="CITI"} }; List<Customer> millionaires = customers.Where(customer => customer.Balance >= 1000000).ToList(); Console.WriteLine("Millionaires: "); foreach (Customer customer in millionaires) { Console.Write($"{customer.Name}, "); } Console.WriteLine(" "); Console.WriteLine(" "); /* Given the same customer set, display how many millionaires per bank. Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq Example Output: WF 2 BOA 1 FTB 1 CITI 1 */ Console.WriteLine("Number of millionaire customers in each bank:"); millionaires.GroupBy(customer => customer.Bank) .ToList() .ForEach(group => { Console.WriteLine($"{group.Key} {group.Count()}"); }); // int wfCustomers = customers.Where(customer => customer.Bank == "WF" && customer.Balance >= 1e6).Count(); // Console.WriteLine($"WF: {wfCustomers}"); // int boaCustomers = customers.Where(customer => customer.Bank == "BOA" && customer.Balance >= 1e6).Count(); // Console.WriteLine($"BOA: {boaCustomers}"); // int ftbCustomers = customers.Where(customer => customer.Bank == "FTB" && customer.Balance >= 1e6).Count(); // Console.WriteLine($"FTB: {ftbCustomers}"); // int citiCustomers = customers.Where(customer => customer.Bank == "CITI" && customer.Balance >= 1e6).Count(); // Console.WriteLine($"CITI: {citiCustomers}"); }
/// <summary> Constructor for a new instance of the Thematic_Headings_AdminViewer class </summary> /// <param name="User"> Authenticated user information </param> /// <param name="Current_Mode"> Mode / navigation information for the current request </param> /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param> /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param> /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param> /// <remarks> Postback from handling an edit or new thematic heading is handled here in the constructor </remarks> public Thematic_Headings_AdminViewer(User_Object User, SobekCM_Navigation_Object Current_Mode, List <Thematic_Heading> Thematic_Headings, Aggregation_Code_Manager Code_Manager, Custom_Tracer Tracer) : base(User) { Tracer.Add_Trace("Thematic_Headings_AdminViewer.Constructor", String.Empty); // Get the current list of thematic headings thematicHeadings = Thematic_Headings; // Save the mode currentMode = Current_Mode; // Set action message to nothing to start actionMessage = String.Empty; // If the user cannot edit this, go back if ((!user.Is_System_Admin) && (!user.Is_Portal_Admin)) { currentMode.Mode = Display_Mode_Enum.My_Sobek; currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home; currentMode.Redirect(); return; } // Handle any post backs if (currentMode.isPostBack) { try { // Pull the standard values from the form NameValueCollection form = HttpContext.Current.Request.Form; string save_value = form["admin_heading_tosave"]; string action_value = form["admin_heading_action"]; // Switch, depending on the request if (action_value != null) { switch (action_value.Trim().ToLower()) { case "edit": string new_name = form["form_heading_name"]; if (new_name != null) { int id = Convert.ToInt32(save_value); int order = 1 + Thematic_Headings.TakeWhile(ThisHeading => ThisHeading.ThematicHeadingID != id).Count(); if (SobekCM_Database.Edit_Thematic_Heading(id, order, new_name, Tracer) < 1) { actionMessage = "Unable to edit existing thematic heading"; } else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } actionMessage = "Thematic heading edits saved"; } } break; case "delete": int thematicDeleteId = Convert.ToInt32(save_value); if (!SobekCM_Database.Delete_Thematic_Heading(thematicDeleteId, Tracer)) { // Set action message actionMessage = "Unable to delete existing thematic heading"; } else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Remove this thematic heading from the list int i = 0; while (i < Thematic_Headings.Count) { if (Thematic_Headings[i].ThematicHeadingID == thematicDeleteId) { Thematic_Headings.RemoveAt(i); } else { i++; } } } // Set action message actionMessage = "Thematic heading deleted"; } break; case "new": int new_order = Thematic_Headings.Count + 1; int newid = SobekCM_Database.Edit_Thematic_Heading(-1, new_order, save_value, Tracer); if (newid < 1) { actionMessage = "Unable to save new thematic heading"; } else { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } // Add this blank thematic heading to the code manager Code_Manager.Add_Blank_Thematic_Heading(newid); actionMessage = "New thematic heading saved"; } break; case "moveup": string[] moveup_split = save_value.Split(",".ToCharArray()); int moveup_id = Convert.ToInt32(moveup_split[0]); int moveup_order = Convert.ToInt32(moveup_split[1]); if (moveup_order > 1) { Thematic_Heading themeHeading = Thematic_Headings[moveup_order - 1]; if (themeHeading.ThematicHeadingID == moveup_id) { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Move this thematic heading up Thematic_Headings.Remove(themeHeading); Thematic_Headings.Insert(moveup_order - 2, themeHeading); int current_order = 1; foreach (Thematic_Heading thisTheme in Thematic_Headings) { SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer); current_order++; } // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } } } break; case "movedown": string[] movedown_split = save_value.Split(",".ToCharArray()); int movedown_id = Convert.ToInt32(movedown_split[0]); int movedown_order = Convert.ToInt32(movedown_split[1]); if (movedown_order < Thematic_Headings.Count) { Thematic_Heading themeHeading = Thematic_Headings[movedown_order - 1]; if (themeHeading.ThematicHeadingID == movedown_id) { // For thread safety, lock the thematic headings list lock (Thematic_Headings) { // Move this thematic heading down Thematic_Headings.Remove(themeHeading); Thematic_Headings.Insert(movedown_order, themeHeading); int current_order = 1; foreach (Thematic_Heading thisTheme in Thematic_Headings) { SobekCM_Database.Edit_Thematic_Heading(thisTheme.ThematicHeadingID, current_order, thisTheme.ThemeName, Tracer); current_order++; } // Repopulate the thematic headings list SobekCM_Database.Populate_Thematic_Headings(Thematic_Headings, Tracer); } } } break; } } } catch (Exception) { actionMessage = "Unknown error caught while handling your reqeust"; } } }
static int Solve(List <Card> arr) { var sorted = arr.OrderBy(x => x.Sign).ToArray(); int[] oddCount = new int[51]; int[] evenCount = new int[51]; for (int i = 0; i < sorted.Length; i++) { if ((i & 1) == 0) { evenCount[sorted[i].Sign]++; } else { oddCount[sorted[i].Sign]++; } } for (int i = 0; i < arr.Count; i++) { if (arr[i].Flipped ^ ((i & 1) == 1)) { if (--oddCount[arr[i].Sign] < 0) { return(int.MaxValue); } } else { if (--evenCount[arr[i].Sign] < 0) { return(int.MaxValue); } } } int step = 0; for (int i = 0; i < arr.Count; i++) { var min = arr.Skip(i).Min(x => x.Sign); var minInd = arr.TakeWhile( (x, y) => y < i || x.Sign != min || (((y - i) & 1) == 1) != x.Flipped ).Count(); if (minInd == arr.Count) { return(int.MaxValue); } var minElem = arr[minInd]; arr.RemoveAt(minInd); arr.Insert(i, minElem); var diff = minInd - i; step += diff; if ((diff & 1) == 1) { arr[i].Flipped ^= true; } for (int j = i + 1; j <= minInd; j++) { arr[j].Flipped ^= true; } if (res <= step) { return(int.MaxValue); } } return(step); }
public async Task GetSnapshotWithoutRestarting(bool includesCompetingSequences, bool includesEvents, bool includesSnapshots, bool endsWithSnapshot) { using (var eventStore = CreateInstance()) { var steps = new List <Step>(); if (includesEvents) { steps.Add(new Step(false, CreateTestData())); } if (includesEvents) { steps.Add(new Step(false, CreateTestData())); } if (includesSnapshots) { steps.Add(new Step(true, CreateTestData())); } if (includesEvents) { steps.Add(new Step(false, CreateTestData())); } if (includesEvents) { steps.Add(new Step(false, CreateTestData())); } if (includesSnapshots) { steps.Add(new Step(true, CreateTestData())); } if (includesEvents) { steps.Add(new Step(false, CreateTestData())); } if (endsWithSnapshot) { steps.Add(new Step(true, CreateTestData())); } var expected = steps .Where(step => step.IsSnapshot) .Select(step => step.Data) .ToList(); var sequences = new List <Sequence> { new Sequence(CompetingSequenceWithSameEntityTypeName.EntityTypeName, CompetingSequenceWithSameEntityId.EntityId, steps.ToImmutableArray(), 0) }; if (includesCompetingSequences) { sequences.Add(CompetingSequenceWithSameEntityTypeName); sequences.Add(CompetingSequenceWithSameEntityId); } await InsertInterleaved(eventStore, sequences.ToImmutableArray()); var actual = new List <ImmutableArray <byte> >(); while (actual.Count < expected.Count()) { actual.Add(await eventStore.GetSnapshot(CompetingSequenceWithSameEntityTypeName.EntityTypeName, CompetingSequenceWithSameEntityId.EntityId, steps.TakeWhile(step => step.Data != expected[actual.Count]).Count(step => !step.IsSnapshot) - 1)); } Assert.Equal(expected, actual); } }
static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> startsWithL = from f in fruits where f.StartsWith("L") select f; foreach (string f in startsWithL) { Console.WriteLine($"{f}"); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0); foreach (int number in fourSixMultiples) { Console.WriteLine($"{number}"); } // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable <string> decend = from name in names orderby name descending select name; foreach (string name in decend) { Console.WriteLine(name); } //List numbers in ascending order (Lowest to Highest) List <int> moreNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> sortedNums = from nums in moreNumbers orderby nums ascending select nums; foreach (int nums in sortedNums) { Console.WriteLine(nums); } // Output how many numbers are in this list List <int> numbers3 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int howMany = numbers3.Count(); Console.WriteLine(howMany); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double totalPurchases = purchases.Sum(); Console.WriteLine($"The sum of all the purchases is ${totalPurchases}"); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double mostExpensive = prices.Max(); Console.WriteLine($"The most expensive product is ${mostExpensive}"); /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; IEnumerable <int> perfSquare = wheresSquaredo.TakeWhile(num => Math.Sqrt(num) % 1 != 0); foreach (int num in perfSquare) { Console.WriteLine($"{num} is not a perfect square"); } //create new list of banks and their symbols List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; //create new list of customers List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Big Ol Dick", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; //writes each customer and their balance and where their account is foreach (Customer cust in customers) { Console.WriteLine($"{cust.Name} has ${cust.Balance} in thier {cust.Bank} account"); } //creates a list of banks var bankList = customers.GroupBy(x => x.Bank); foreach (var bankMills in bankList) { Console.WriteLine("{0} - {1}", bankMills.Key, bankMills.Count(x => x.Balance >= 1000000)); } IEnumerable <Customer> millionairs = from customer in customers where customer.Balance >= 1000000 select customer; foreach (Customer millionair in millionairs) { Console.WriteLine(millionair.Name); } var MillionairReport = from millionair in millionairs join bank in banks on millionair.Bank equals bank.Symbol select new { Millionair = millionair.Name, Bank = bank.Name }; foreach (var ballers in MillionairReport) { Console.WriteLine(ballers.Millionair + " " + ballers.Bank); } }
internal void update() { tickCount = (tickCount + 1) % TicksPerScroll; if (onScreen.Count > 0 && tickCount == 0) { foreach (Text t in onScreen) { t.Pos.Y -= 1; } Sprite fst = onScreen.First(); if (fst.Pos.Y < Pos.Y) { This.Game.CurrentLevel.RemoveSprite(fst); onScreen.RemoveAt(0); } } if (buffer.Count != 0) { // We have room to scroll another line of text if (onScreen.Count == 0 || onScreen.Last().Pos.Y + onScreen.Last().GetAnimation().Height + TextSpacing < Pos.Y + GetAnimation().Height - onScreen.Last().GetAnimation().Height) { int width = GetAnimation().Width; string toDisplay; if (String.Join("", buffer.Take(2)) == "\n\n") { toDisplay = " "; buffer.RemoveRange(0, 2); } else { buffer = buffer.SkipWhile(x => char.IsWhiteSpace(x)).ToList(); IEnumerable<char> pendingDisplay = buffer.TakeWhile((ch, ix) => theme.TextFont.MeasureString( String.Join("", buffer.Take(ix + 1)).Trim()).X < width && ch != '\n'); if (SplitOnWhitespace && buffer.Count > pendingDisplay.Count() && buffer[pendingDisplay.Count()] != '\n') { // Find first instance of whitespace at end pendingDisplay = pendingDisplay.Reverse().SkipWhile(x => !char.IsWhiteSpace(x)).Reverse(); } toDisplay = String.Join("", pendingDisplay).Trim(); buffer.RemoveRange(0, pendingDisplay.Count()); } Text line = new Text("text", theme.TextFont, toDisplay.ToString()); line.DisplayColor = theme.TextColor; line.Pos = new Vector2(Pos.X, Pos.Y + GetAnimation().Height - line.GetAnimation().Height); line.Static = true; line.ZOrder = 101; onScreen.Add(line); } } }
static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = fruits.Where(fruit => fruit.StartsWith("L")); Console.WriteLine("Get foods that start with the letter 'L'"); Console.WriteLine("---------------------"); LFruits.ToList().ForEach(LFruit => Console.WriteLine(LFruit)); // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(num => num % 4 == 0 || num % 6 == 0); Console.WriteLine(); Console.WriteLine("Get numbers that are multiples of 4 or 6"); Console.WriteLine("---------------------"); fourSixMultiples.ToList().ForEach(num => Console.WriteLine(num)); // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable <string> descendingNames = names.OrderByDescending(name => name); Console.WriteLine(); Console.WriteLine("Get names in descending order"); Console.WriteLine("---------------------"); descendingNames.ToList().ForEach(name => Console.WriteLine(name)); // Build a collection of these numbers sorted in ascending order List <int> sortNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine(); Console.WriteLine("Sort numbers in ascending order"); Console.WriteLine("---------------------"); IEnumerable <int> ascendingNumbers = sortNumbers.OrderBy(num => num); ascendingNumbers.ToList().ForEach(num => Console.WriteLine(num)); // Output how many numbers are in this list List <int> countNumbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int numberCount = countNumbers.Count; Console.WriteLine(); Console.WriteLine("Count how many numbers are in a list"); Console.WriteLine("---------------------"); Console.WriteLine(numberCount); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double moneyMade = purchases.Sum(); Console.WriteLine(); Console.WriteLine("How much money have we made?"); Console.WriteLine("---------------------"); Console.WriteLine($"${moneyMade}"); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; IEnumerable <double> sortedPrices = prices.OrderByDescending(num => num); double mostExpensive = sortedPrices.FirstOrDefault(); Console.WriteLine(); Console.WriteLine("Most expensive product"); Console.WriteLine("---------------------"); Console.WriteLine($"${mostExpensive}"); List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; /* * Store each number in the following List until a perfect square * is detected. * * Expected output is { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46 } * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ IEnumerable <int> numberList = wheresSquaredo.TakeWhile(num => Math.Sqrt(num) % 1 != 0); Console.WriteLine(); Console.WriteLine("Store each number until a perfect square is detected"); Console.WriteLine("---------------------"); numberList.ToList().ForEach(num => Console.WriteLine(num)); /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq * * Example Output: * WF 2 * BOA 1 * FTB 1 * CITI 1 */ List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; List <Bank> bankMills = (from customer in customers group customer by customer.Bank into bankGroup select new Bank { Name = bankGroup.Key, CurrentMills = bankGroup.Count() }).ToList(); Console.WriteLine(); Console.WriteLine("Display how many millionaires per bank"); Console.WriteLine("---------------------"); foreach (Bank bank in bankMills) { Console.WriteLine($"{bank.Name}: {bank.CurrentMills}"); } }
static void Main(string[] args) { // ----- RESTRICTION/FILTERING OPTIONS ----- // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from fruit in fruits where fruit.StartsWith("L") select fruit; foreach (string fruit in LFruits) { // Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(n => n % 4 == 0 || n % 6 == 0); foreach (int num in fourSixMultiples) { // Console.WriteLine(num); } // ----- ORDERING OPERATIONS ----- // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List <string> descend = names.OrderByDescending(name => name).ToList(); foreach (string name in descend) { // Console.WriteLine(name); } // Build a collection of these numbers sorted in ascending order List <int> numbers2 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List <int> numbersOrdered = numbers2.OrderBy(n => n).ToList(); foreach (int num in numbersOrdered) { // Console.WriteLine(num); } // ----- AGGREGATE OPERATIONS ----- // Output how many numbers are in this list List <int> numbers3 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int numCount = numbers3.Count(); // Console.WriteLine(numCount); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double totalMoney = purchases.Sum(); // Console.WriteLine(totalMoney); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double mostExpensiveProduct = prices.OrderByDescending(price => price).ToList()[0]; // Console.WriteLine(mostExpensiveProduct); // ----- PARTITIONING OPERATIONS ----- /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; List <int> noSquares = wheresSquaredo.TakeWhile(n => Math.Sqrt(n) % 1 != 0).ToList(); foreach (int num in noSquares) { // Console.WriteLine(num); } // ----- USING CUSTOM TYPES ----- List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq * * Example Output: * WF 2 * BOA 1 * FTB 1 * CITI 1 */ List <Customer> listOfMillionaires = customers.Where(c => c.Balance >= 1000000).ToList(); var millionairesPerBank = listOfMillionaires.GroupBy( millionaire => millionaire.Bank, millionaire => millionaire, (key, value) => new { BankName = key, MillionaireCount = value.Count() }); foreach (var count in millionairesPerBank) { // Console.WriteLine($"{count.BankName}: {count.MillionaireCount}"); } // ----- CHALLENGE: Introduction to Joining Two Related Collections ----- /* * TASK: * As in the previous exercise, you're going to output the millionaires, * but you will also display the full name of the bank. You also need * to sort the millionaires' names, ascending by their LAST name. * * Example output: * Tina Fey at Citibank * Joe Landy at Wells Fargo * Sarah Ng at First Tennessee * Les Paul at Wells Fargo * Peg Vale at Bank of America */ List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; /* * You will need to use the `Where()` * and `Select()` methods to generate * instances of the following class. * * public class ReportItem * { * public string CustomerName { get; set; } * public string BankName { get; set; } * } */ // var millionairesAndBanks = // from m in listOfMillionaires // join b in banks on m.Bank equals b.Symbol // select new ReportItem { CustomerName = m.Name, BankName = b.Name }; List <ReportItem> millionaireReport = listOfMillionaires.Join( banks, millionaire => millionaire.Bank, bank => bank.Symbol, (key, value) => new ReportItem { CustomerName = key.Name, BankName = value.Name }) .ToList(); foreach (var item in millionaireReport) { Console.WriteLine($"{item.CustomerName} at {item.BankName}"); } }
/// <summary> /// Traverse AssistStructure and add ViewNode metadata to a flat list. /// </summary> /// <returns>The parse.</returns> /// <param name="forFill">If set to <c>true</c> for fill.</param> /// <param name="isManualRequest"></param> string Parse(bool forFill, bool isManualRequest) { CommonUtil.logd("Parsing structure for " + Structure.ActivityComponent); var nodes = Structure.WindowNodeCount; ClientFormData = new FilledAutofillFieldCollection(); String webDomain = null; _editTextsWithoutHint.Clear(); for (int i = 0; i < nodes; i++) { var node = Structure.GetWindowNodeAt(i); var view = node.RootViewNode; ParseLocked(forFill, isManualRequest, view, ref webDomain); } List <AssistStructure.ViewNode> passwordFields = new List <AssistStructure.ViewNode>(); List <AssistStructure.ViewNode> usernameFields = new List <AssistStructure.ViewNode>(); if (AutofillFields.Empty) { passwordFields = _editTextsWithoutHint.Where(IsPassword).ToList(); if (!passwordFields.Any()) { passwordFields = _editTextsWithoutHint.Where(HasPasswordHint).ToList(); } foreach (var passwordField in passwordFields) { var usernameField = _editTextsWithoutHint.TakeWhile(f => f.AutofillId != passwordField.AutofillId).LastOrDefault(); if (usernameField != null) { usernameFields.Add(usernameField); } } //for some pages with two-step login, we don't see a password field and don't display the autofill for non-manual requests. But if the user forces autofill, //let's assume it is a username field: if (isManualRequest && !passwordFields.Any() && _editTextsWithoutHint.Count == 1) { usernameFields.Add(_editTextsWithoutHint.First()); } } //force focused fields to be included in autofill fields when request was triggered manually. This allows to fill fields which are "off" or don't have a hint (in case there are hints) if (isManualRequest) { foreach (AssistStructure.ViewNode editText in _editTextsWithoutHint) { if (editText.IsFocused) { if (IsPassword(editText) || HasPasswordHint(editText)) { passwordFields.Add(editText); } else { usernameFields.Add(editText); } break; } } } if (forFill) { foreach (var uf in usernameFields) { AutofillFields.Add(new AutofillFieldMetadata(uf, new[] { View.AutofillHintUsername })); } foreach (var pf in passwordFields) { AutofillFields.Add(new AutofillFieldMetadata(pf, new[] { View.AutofillHintPassword })); } } else { foreach (var uf in usernameFields) { ClientFormData.Add(new FilledAutofillField(uf, new[] { View.AutofillHintUsername })); } foreach (var pf in passwordFields) { ClientFormData.Add(new FilledAutofillField(pf, new[] { View.AutofillHintPassword })); } } String packageName = Structure.ActivityComponent.PackageName; if (!string.IsNullOrEmpty(webDomain)) { bool valid = Kp2aDigitalAssetLinksDataSource.Instance.IsValid(mContext, webDomain, packageName); if (!valid) { CommonUtil.loge($"DAL verification failed for {packageName}/{webDomain}"); webDomain = null; } } if (string.IsNullOrEmpty(webDomain)) { webDomain = "androidapp://" + packageName; CommonUtil.logd("no web domain. Using package name."); } return(webDomain); }
static void Main(string[] args) { // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = fruits.Where(n => n.StartsWith("L")); foreach (string fruit in LFruits) { Console.WriteLine(fruit); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(n => n % 4 == 0 || n % 6 == 0); foreach (int number in fourSixMultiples) { Console.WriteLine(number); } // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; List <string> descend = names.OrderByDescending(n => n).ToList(); foreach (string word in descend) { Console.WriteLine(word); } // Build a collection of these numbers sorted in ascending order List <int> numbersup = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; List <int> numbersAscending = numbersup.OrderBy(n => n).ToList(); foreach (int number in numbersAscending) { Console.WriteLine(number); } // Output how many numbers are in this list List <int> numbersCount = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; int countedNumbers = numbersCount.Count(); Console.WriteLine(countedNumbers); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; double sumPurchases = purchases.Sum(); Console.WriteLine(sumPurchases); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; double maxPrice = prices.Max(); Console.WriteLine(maxPrice); /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 9, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; List <int> stopSquare = wheresSquaredo.TakeWhile(n => Math.Sqrt(n) % 1 != 0).ToList(); foreach (int item in stopSquare) { Console.WriteLine(item); } List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq * * Example Output: * WF 2 * BOA 1 * FTB 1 * CITI 1 */ List <Customer> millionaires = customers.Where(n => n.Balance > 999999).ToList(); var results = millionaires.GroupBy( n => n.Bank, n => n.Name, (key, g) => new { Bank = key, Name = g.ToList() } ); foreach (var item in results) { //count how many name items appear in each bank and display the count int counted = item.Name.Count(); Console.WriteLine($"{item.Bank} {counted}"); } }
/// <summary>Check whether there are commands that can be removed from the flight computer command queue (when their delay time has elapsed).</summary> /// <remarks>This is done during the Update() phase of the game engine. <see cref="OnUpdate"/> method.</remarks> private void PopCommand() { // something in command queue? if (_commandQueue.Count <= 0) { return; } // Can come out of time warp even if ship is not powered; workaround for KSP 0.24 power consumption bug if (RTSettings.Instance.ThrottleTimeWarp && TimeWarp.CurrentRate > 4.0f) { var time = TimeWarp.deltaTime; foreach (var dc in _commandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime + (2 * time + 1.0))) { var message = new ScreenMessage(Localizer.Format("#RT_FC_msg1"), 4.0f, ScreenMessageStyle.UPPER_LEFT); //"[Flight Computer]: Throttling back time warp..." while ((2 * TimeWarp.deltaTime + 1.0) > (Math.Max(dc.TimeStamp - RTUtil.GameTime, 0) + dc.ExtraDelay) && TimeWarp.CurrentRate > 1.0f) // { TimeWarp.SetRate(TimeWarp.CurrentRateIndex - 1, true); ScreenMessages.PostScreenMessage(message); } } } // Proceed the extraDelay for every command where the normal delay is over foreach (var dc in _commandQueue.Where(s => s.Delay == 0).ToList()) { // Use time decrement instead of comparing scheduled time, in case we later want to // reinstate event clocks stopping under certain conditions if (dc.ExtraDelay > 0) { //issue: deltaTime is floating point -/+0.001, not great for long-term time-senitive operation if (dc.ExtraDelayScheduledTimeStamp > RTUtil.GameTime) { dc.ExtraDelay = dc.ExtraDelayScheduledTimeStamp - RTUtil.GameTime; } else //fallback { dc.ExtraDelay -= TimeWarp.deltaTime; } } else { if (SignalProcessor.Powered) { // Note: depending on implementation, dc.Pop() may execute the event if (dc.Pop(this)) { _activeCommands[dc.Priority] = dc; if (OnNewCommandPop != null) { OnNewCommandPop.Invoke(); } } } else { string message = Localizer.Format("#RT_FC_msg2", dc.ShortName);//$"[Flight Computer]: Out of power, cannot run \"{}\" on schedule." ScreenMessages.PostScreenMessage(new ScreenMessage( message, 4.0f, ScreenMessageStyle.UPPER_LEFT)); } _commandQueue.Remove(dc); UpdateLastTarget(); } } }
private bool posh() { List<Tuple<int, int>> degree = new List<Tuple<int, int>>(); for(int i = 0; i < v; ++i) { Tuple<int, int> pair = new Tuple<int, int>(i, graph.AdjacentDegree(i)); degree.Add(pair); } degree.Sort((x, y) => x.Item2.CompareTo(y.Item2)); int mid = (v - 1) / 2; for (int k = 0; k < mid; ++k) { if (!(degree.TakeWhile(item => item.Item2 < k).Count()<k)) { return false; } } if (v % 2 == 1 && degree.TakeWhile(item => item.Item2 == mid).Count() > mid) { return false; } return true; }
static void Main(string[] args) { // Given the collections of items shown below, use LINQ to build the requested collection, and then Console.WriteLine() each item in that resulting collection. // Restriction/Filtering Operations // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; IEnumerable <string> LFruits = from taco in fruits where taco.StartsWith("L") select taco; foreach (String taco in LFruits) { Console.WriteLine($"{taco}"); } // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> fourSixMultiples = numbers.Where(n => n % 4 == 0 || n % 6 == 0); foreach (int taco in fourSixMultiples) { Console.WriteLine($"{taco}"); } // Ordering Operations // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; IEnumerable <string> descend = from taco in names orderby taco descending select taco; foreach (string taco in descend) { Console.WriteLine($"{taco}"); } // Build a collection of these numbers sorted in ascending order List <int> numbers2 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; IEnumerable <int> ascend = from taco in numbers2 orderby taco ascending select taco; foreach (int taco in ascend) { Console.WriteLine($"{taco}"); } // Aggregate Operations // Output how many numbers are in this list List <int> numbers3 = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"There are {numbers3.Count} numbers in numbers3"); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; Console.WriteLine($"the sum of purchases is {purchases.Sum()}"); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; Console.WriteLine($"The most expensive product is {prices.Max()}"); // Partitioning Operations /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> wheresSquaredo = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; IEnumerable <int> numsUntilPerfectSquare = wheresSquaredo.TakeWhile(n => n % Math.Sqrt(n) != 0); // List<int> untilPerfectSquareFound = wheresSquaredo.TakeWhile(number => Math.Sqrt(number) % 1 != 0).ToList(); foreach (int taco in numsUntilPerfectSquare) { Console.WriteLine($"{taco}"); } // Using Custom Types // // Build a collection of customers who are millionaires List <Customer> customers = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; IEnumerable <Customer> millionaires = customers.Where(taco => taco.Balance >= 1000000); foreach (Customer taco in millionaires) { Console.WriteLine($"{taco.Name}"); } // Given the same customer set, display how many millionaires per bank. // Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq // Example Output: // WF 2 // BOA 1 // FTB 1 // CITI 1 List <BankReportEntry> BankReport = (from taco in millionaires group taco by taco.Bank into BankGroup select new BankReportEntry { ReportBank = BankGroup.Key, MillionairesInBank = BankGroup.Count() } ).OrderByDescending(br => br.MillionairesInBank).ToList(); foreach (BankReportEntry taco in BankReport) { Console.WriteLine($" Bank: {taco.ReportBank}, Balance: {taco.MillionairesInBank}"); } // Dictionary<string, int> results = new Dictionary<string, int>(); // results.Add(millionaires.GroupBy( // p => p.Bank, // (taco, g) => { taco, g.Count()}); var results = millionaires.GroupBy( p => p.Bank, (key, g) => new { Bank = key, p = g.Count() }); foreach (var item in results) { Console.WriteLine(item); } // Introduction to Joining Two Related Collections // As a light introduction to working with relational databases, this example works with two collections of data - banks and customers - that are related through the Bank attribute on the customer. In that attribute, we store the abbreviation for a bank. However, we want to get the full name of the bank when we produce our output. // This is called joining the collections together. // This exercise is also an introduction to producing anonymous objects as the result of the LINQ statement. // Read the Group Join example to get started. // TASK: // As in the previous exercise, you're going to output the millionaires, // but you will also display the full name of the bank. You also need // to sort the millionaires' names, ascending by their LAST name. // Example output: // Tina Fey at Citibank // Joe Landy at Wells Fargo // Sarah Ng at First Tennessee // Les Paul at Wells Fargo // Peg Vale at Bank of America // Create some banks and store in a List List <Bank> banks = new List <Bank>() { new Bank() { Name = "First Tennessee", Symbol = "FTB" }, new Bank() { Name = "Wells Fargo", Symbol = "WF" }, new Bank() { Name = "Bank of America", Symbol = "BOA" }, new Bank() { Name = "Citibank", Symbol = "CITI" }, }; // Create some customers and store in a List List <Customer> customers2 = new List <Customer>() { new Customer() { Name = "Bob Lesman", Balance = 80345.66, Bank = "FTB" }, new Customer() { Name = "Joe Landy", Balance = 9284756.21, Bank = "WF" }, new Customer() { Name = "Meg Ford", Balance = 487233.01, Bank = "BOA" }, new Customer() { Name = "Peg Vale", Balance = 7001449.92, Bank = "BOA" }, new Customer() { Name = "Mike Johnson", Balance = 790872.12, Bank = "WF" }, new Customer() { Name = "Les Paul", Balance = 8374892.54, Bank = "WF" }, new Customer() { Name = "Sid Crosby", Balance = 957436.39, Bank = "FTB" }, new Customer() { Name = "Sarah Ng", Balance = 56562389.85, Bank = "FTB" }, new Customer() { Name = "Tina Fey", Balance = 1000000.00, Bank = "CITI" }, new Customer() { Name = "Sid Brown", Balance = 49582.68, Bank = "CITI" } }; /* * You will need to use the `Where()` * and `Select()` methods to generate * instances of the following class. * * public class ReportItem * { * public string CustomerName { get; set; } * public string BankName { get; set; } * } */ List <ReportItem> millionaireNamesSorted = customers2 .Where(taco => taco.Balance >= 1000000) .OrderBy(taco => taco.Name.Split(" ")[1]) .Select(taco => new ReportItem { CustomerName = taco.Name, BankName = banks.First(bankTaco => bankTaco.Symbol == taco.Bank).Name }) .ToList(); foreach (ReportItem taco in millionaireNamesSorted) { Console.WriteLine($"{taco.CustomerName} {taco.BankName}"); } }
public static void Main() { List<int> collection = new List<int> {1, 2, 3, 4, 6, 11, 3}; Console.WriteLine(string.Join(", ", collection.TakeWhile(x => x < 10))); }
/// <summary> /// Traverse AssistStructure and add ViewNode metadata to a flat list. /// </summary> /// <returns>The parse.</returns> /// <param name="forFill">If set to <c>true</c> for fill.</param> /// <param name="isManualRequest"></param> AutofillTargetId Parse(bool forFill, bool isManualRequest) { AutofillTargetId result = new AutofillTargetId(); CommonUtil.logd("Parsing structure for " + Structure.ActivityComponent); var nodes = Structure.WindowNodeCount; ClientFormData = new FilledAutofillFieldCollection(); String webDomain = null; _editTextsWithoutHint.Clear(); for (int i = 0; i < nodes; i++) { var node = Structure.GetWindowNodeAt(i); var view = node.RootViewNode; ParseLocked(forFill, isManualRequest, view, ref webDomain); } List <AssistStructure.ViewNode> passwordFields = new List <AssistStructure.ViewNode>(); List <AssistStructure.ViewNode> usernameFields = new List <AssistStructure.ViewNode>(); if (AutofillFields.Empty) { passwordFields = _editTextsWithoutHint.Where(IsPassword).ToList(); if (!passwordFields.Any()) { passwordFields = _editTextsWithoutHint.Where(HasPasswordHint).ToList(); } usernameFields = _editTextsWithoutHint.Where(HasUsernameHint).ToList(); if (usernameFields.Any() == false) { foreach (var passwordField in passwordFields) { var usernameField = _editTextsWithoutHint .TakeWhile(f => f.AutofillId != passwordField.AutofillId).LastOrDefault(); if (usernameField != null) { usernameFields.Add(usernameField); } } } if (usernameFields.Any() == false) { //for some pages with two-step login, we don't see a password field and don't display the autofill for non-manual requests. But if the user forces autofill, //let's assume it is a username field: if (isManualRequest && !passwordFields.Any() && _editTextsWithoutHint.Count == 1) { usernameFields.Add(_editTextsWithoutHint.First()); } } } //force focused fields to be included in autofill fields when request was triggered manually. This allows to fill fields which are "off" or don't have a hint (in case there are hints) if (isManualRequest) { foreach (AssistStructure.ViewNode editText in _editTextsWithoutHint) { if (editText.IsFocused) { if (IsPassword(editText) || HasPasswordHint(editText)) { passwordFields.Add(editText); } else { usernameFields.Add(editText); } break; } } } if (forFill) { foreach (var uf in usernameFields) { AutofillFields.Add(new AutofillFieldMetadata(uf, new[] { View.AutofillHintUsername })); } foreach (var pf in passwordFields) { AutofillFields.Add(new AutofillFieldMetadata(pf, new[] { View.AutofillHintPassword })); } } else { foreach (var uf in usernameFields) { ClientFormData.Add(new FilledAutofillField(uf, new[] { View.AutofillHintUsername })); } foreach (var pf in passwordFields) { ClientFormData.Add(new FilledAutofillField(pf, new[] { View.AutofillHintPassword })); } } result.WebDomain = webDomain; result.PackageName = Structure.ActivityComponent.PackageName; if (!string.IsNullOrEmpty(webDomain) && !PreferenceManager.GetDefaultSharedPreferences(mContext).GetBoolean(mContext.GetString(Resource.String.NoDalVerification_key), false)) { result.IncompatiblePackageAndDomain = !kp2aDigitalAssetLinksDataSource.IsTrustedLink(webDomain, result.PackageName); if (result.IncompatiblePackageAndDomain) { CommonUtil.loge($"DAL verification failed for {result.PackageName}/{result.WebDomain}"); } } else { result.IncompatiblePackageAndDomain = false; } return(result); }
public async Task <IReadOnlyCollection <TradeHistoryItem> > GetNextBatchAsync() { // If we got the last batch in the previous iteration, there is no reason to execute one more query // with empty result. Just return. if (_gotTheLastBatch) { return(Array.Empty <TradeHistoryItem>()); } try { var result = new List <TradeHistoryItem>(); // Renew the connection on every call. using (var sqlConnection = new SqlConnection(_sqlConnString)) { sqlConnection.Open(); if (sqlConnection.State != ConnectionState.Open) { throw new InvalidOperationException("Can't fetch from DB while connection is not opened."); } await _log.WriteInfoAsync(nameof(GetNextBatchAsync), $"Starting offset = {StartingRowOffset}, asset pair ID = {AssetPairId}", $"Trying to fetch next {_sqlQueryBatchSize} rows..."); using (var sqlCommand = BuildCurrentQueryCommand(sqlConnection)) { sqlCommand.CommandTimeout = (int)_sqlTimeout.TotalSeconds; using (var reader = await sqlCommand.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var trade = new TradeHistoryItem { Id = reader.GetInt64(0), AssetToken = reader.GetString(1), Direction = (TradeDirection)Enum.Parse(typeof(TradeDirection), reader.GetString(2)), Volume = reader.GetDecimal(3), Price = reader.GetDecimal(4), DateTime = reader.GetDateTime(5), OppositeVolume = reader.GetDecimal(6), OrderId = Guid.Parse(reader.GetString(7)), OppositeOrderId = Guid.Parse(reader.GetString(8)), TradeId = reader.GetString(9), IsStraight = reader.GetString(1) == SearchToken // If the trade is straight or reverse. }; // We must ignore trades with negative prices and\or volumes (if any). if (trade.Price > 0 && trade.Volume > 0 && trade.OppositeVolume > 0) { result.Add(trade); } else { await _log.WriteMonitorAsync(nameof(GetNextBatchAsync), trade.ToJson(), "Got a trade with non-posotive price or volume(s) values."); } } } } sqlConnection.Close(); } if (result.Count > 0) { // Now we need to remove the last several trades which have the same date and time (accuracy - to seconds). // This will guarantee that we did not peek up some orders of the same trade on this iteration, and others // on the next. On the next iteration we will read them again for the next batch. No temporary buffer, for // it can't save any observable value of time. NOTE: if we have got less records than _sqlQueryBatchSize, // this means that we obtained the last (or the single) data pack, and there is no reason to delete "tail" // trades. if (result.Count == _sqlQueryBatchSize) { var lastDateTime = result.Last().DateTime.TruncateTo(CandleTimeInterval.Sec); var resultWithoutTail = result.TakeWhile(t => t.DateTime < lastDateTime).ToList(); if (!resultWithoutTail.Any()) { throw new InvalidOperationException($"Got an SQL data batch of {result.Count} trade records with the same timestamp {lastDateTime:O}. " + $"Migration for asset pair {AssetPairId} will be terminated. Row offset was {StartingRowOffset} before the incident."); } result = resultWithoutTail; } else { _gotTheLastBatch = true; // If we have got smaller amount of records than _sqlQueryBatchSize, this only means we have the last batch now. } await _log.WriteInfoAsync(nameof(GetNextBatchAsync), $"Starting offset = {StartingRowOffset}, asset pair ID = {AssetPairId}", $"Fetched {result.Count} rows successfully. First date is {result.First().DateTime:O}, last date is {result.Last().DateTime:O}"); StartingRowOffset += result.Count; } else { await _log.WriteInfoAsync(nameof(GetNextBatchAsync), $"Starting offset = {StartingRowOffset}, asset pair ID = {AssetPairId}", "No data to fetch."); } return(result); } catch (Exception ex) { await _log.WriteErrorAsync(nameof(GetNextBatchAsync), string.Empty, ex); // We can just report about the error and return an empty list - this will be interpreted as "no data". return(Array.Empty <TradeHistoryItem>()); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); // Find the words in the collection that start with the letter 'L' List <string> fruits = new List <string>() { "Lemon", "Apple", "Orange", "Lime", "Watermelon", "Loganberry" }; var LFruits = from fruit in fruits where fruit.First() == 'L' select fruit; LFruits.ToList().ForEach(Console.WriteLine); // Which of the following numbers are multiples of 4 or 6 List <int> numbers = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; var fourSixMultiples = numbers.Where(number => number % 4 == 0 || number % 6 == 0); fourSixMultiples.ToList().ForEach(Console.WriteLine); // Order these student names alphabetically, in descending order (Z to A) List <string> names = new List <string>() { "Heather", "James", "Xavier", "Michelle", "Brian", "Nina", "Kathleen", "Sophia", "Amir", "Douglas", "Zarley", "Beatrice", "Theodora", "William", "Svetlana", "Charisse", "Yolanda", "Gregorio", "Jean-Paul", "Evangelina", "Viktor", "Jacqueline", "Francisco", "Tre" }; names.OrderByDescending(name => name).ToList().ForEach(Console.WriteLine); // Build a collection of these numbers sorted in ascending order List <int> numeros = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; numeros.OrderBy(numero => numero).ToList().ForEach(Console.WriteLine); // Output how many numbers are in this list List <int> nombres = new List <int>() { 15, 8, 21, 24, 32, 13, 30, 12, 7, 54, 48, 4, 49, 96 }; Console.WriteLine($"There are {nombres.Count()} numbers in this list."); // How much money have we made? List <double> purchases = new List <double>() { 2340.29, 745.31, 21.76, 34.03, 4786.45, 879.45, 9442.85, 2454.63, 45.65 }; Console.WriteLine($"Purchases = ${purchases.Sum()}"); // What is our most expensive product? List <double> prices = new List <double>() { 879.45, 9442.85, 2454.63, 45.65, 2340.29, 34.03, 4786.45, 745.31, 21.76 }; Console.WriteLine($"The maximum price is {prices.Max()}"); /* * Store each number in the following List until a perfect square * is detected. * * Ref: https://msdn.microsoft.com/en-us/library/system.math.sqrt(v=vs.110).aspx */ List <int> notPerfectSquares = new List <int>() { 66, 12, 8, 27, 82, 34, 7, 50, 19, 46, 81, 23, 30, 4, 68, 14 }; notPerfectSquares.TakeWhile(notPerfectSquare => notPerfectSquare % 1 != 0).ToList().ForEach(Console.WriteLine); /* * Given the same customer set, display how many millionaires per bank. * Ref: https://stackoverflow.com/questions/7325278/group-by-in-linq * * Example Output: * WF 2 * BOA 1 * FTB 1 * CITI 1 */ // Build a collection of customers who are millionaires customers .Where(Customer => Customer.Balance > 999999.99) .GroupBy(Customer => Customer.Bank).ToList() .ForEach(x => Console.WriteLine($"{x.Key} has {x.Count()} millionaires!")); /* As a light introduction to working with relational databases, this example works with two collections of * data - `banks` and `customers` - that are related through the `Bank` attribute on the customer. In that * attribute, we store the abbreviation for a bank. However, we want to get the full name of the bank when we * produce our output. * * This is called joining the collections together. * * This exercise is also an introduction to producing anonymous objects as the result of the LINQ statement. * * Read the [Group Join](https://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9#groupjoin) example to * get started. */ /* * TASK: * As in the previous exercise, you're going to output the millionaires, * but you will also display the full name of the bank. You also need * to sort the millionaires' names, ascending by their LAST name. * * Example output: * Tina Fey at Citibank * Joe Landy at Wells Fargo * Sarah Ng at First Tennessee * Les Paul at Wells Fargo * Peg Vale at Bank of America */ // Define a bank // Create some banks and store in a List // var millionaireReport = ... // foreach (var customer in millionaireReport) // { // Console.WriteLine($"{customer.Name} at {customer.Bank}"); // } banks .Join(customers, b => b.Symbol, c => c.Bank, (bank, customer) => new { CustomerName = customer.Name, CustomberBalance = customer.Balance, BankName = bank.Name } ) .Where(CustomerInfo => CustomerInfo.CustomberBalance > 999999.99) .OrderBy(Customer => Customer.CustomerName.Split(' ')[1]).ToList() .ForEach(CustomerAtBank => Console.WriteLine($"{CustomerAtBank.CustomerName} at {CustomerAtBank.BankName}")); }