linq-to-objects

Recursive control search with LINQ

浪子不回头ぞ 提交于 2019-11-26 03:57:40
问题 If I wanted to find checked check boxes on an ASP.NET page I could use the following LINQ query. var checkBoxes = this.Controls .OfType<CheckBox>() .TakeWhile<CheckBox>(cb => cb.Checked); That works fine if the checkboxes are nested in the current control collection, but I\'d like to know how to extend the search by drilling down into the control collections of the top-level controls. The question was asked here: Finding controls that use a certain interface in ASP.NET And received non-LINQ

Sorting a list using Lambda/Linq to objects

吃可爱长大的小学妹 提交于 2019-11-26 03:34:56
问题 I have the name of the \"sort by property\" in a string. I will need to use Lambda/Linq to sort the list of objects. Ex: public class Employee { public string FirstName {set; get;} public string LastName {set; get;} public DateTime DOB {set; get;} } public void Sort(ref List<Employee> list, string sortBy, string sortDirection) { //Example data: //sortBy = \"FirstName\" //sortDirection = \"ASC\" or \"DESC\" if (sortBy == \"FirstName\") { list = list.OrderBy(x => x.FirstName).toList(); } }

Remove duplicates in the list using linq

房东的猫 提交于 2019-11-26 00:06:59
问题 I have a class Items with properties (Id, Name, Code, Price) . The List of Items is populated with duplicated items. For ex.: 1 Item1 IT00001 $100 2 Item2 IT00002 $200 3 Item3 IT00003 $150 1 Item1 IT00001 $100 3 Item3 IT00003 $150 How to remove the duplicates in the list using linq? 回答1: var distinctItems = items.Distinct(); To match on only some of the properties, create a custom equality comparer, e.g.: class DistinctItemComparer : IEqualityComparer<Item> { public bool Equals(Item x, Item y

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

橙三吉。 提交于 2019-11-25 21:36:54
问题 I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a sql-like string (e.g. OrderBy(\"Name, Age DESC\")) for ordering. Unfortunately, the method included only works on IQueryable<T> ;. Is there any way to get this functionality on IEnumerable<T> ? 回答1: Just stumbled into this oldie... To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with IEnumerable<T>