29Jul/090
Using Link to sort listbox content
This is a great way to sort lists for listboxes and other UIElements.
LINQ will only sort specific types of lists.
// Must use Linq
using System.Linq;
.
.
.
// Your list
ObservableCollection<MyObject> myList = new ObservableCollection<MyObject>();
// Your listbox
ListBox listBox = new ListBox();
// Sorting is done like this
listBox.ItemsSource = (from MyObject o in myList
where o.Name.ToLower().Contains(textboxNameSearch.Text.ToLower())
|| o.Address.ToLower().Contains(textboxAddressSearch.Text.ToLower())
select o);
23Jul/090
using AsQueryable().Where() to filter data
Sorting lists using AsQueryable:
This uses both System.Linq and System.Linq.Dynamic
List testList = new List()
{
new TestClass
{
ID = 1,
Name = "David",
Other = "other"
},
new TestClass
{
ID = 2,
Name = "James",
Other = "other"
},
new TestClass
{
ID = 3,
Name = "Darren",
Other = "some"
},
};
string searchString = " (Name == \"James\" AND Other == \"other\") Or (Name == \"Darren\") ";
var queryResult = testList.AsQueryable().Where(searchString);
The extra Class:
class TestClass
{
public int ID {get; set;}
public string Name {get; set;}
public string Other {get; set;}
}
23Jul/090
Casting a List of objects
Casting a list of objects is as simple as (using Linq):
List masterList = new List(); var list = masterList.Cast();
If you don't know the type to cast to, it becomes a bit difficult.
MethodInfo m = typeof(System.Linq.Enumerable).GetMethod("Cast").MakeGenericMethod(new Type[] { typeof(Href) });
var result = m.Invoke(typeof(System.Linq.Enumerable), new object[] { masterList });
This works just fine.
However, the result is not a list. This would not be a problem normally. You would just add a .ToList() to the end.
List masterList = new List(); var list = masterList.Cast().ToList();
This does not work the generic way. I thought another Invoke would do the trick. I could not figure out to do that.
Instead I opted for a more simple option. I created a generic method as such:
public void newMethod()
{
var list = masterList .Cast().ToList();
}
To cast a type list you just add the type.
List<object> oList = new List<object>(); List<string> sList = new List<string>(); sList = oList.Cast<string>.ToList();