日期:2014-05-20 浏览次数:20781 次
string s="name"; if(s=="name") { var q =( from e in db.Student orderby e.name select e.name).Distinct(); } else if(s=="age") { var q = (from e in db.Student orderby e.age select e.age).Distinct();; }
------解决方案--------------------
public class Person
{
public string FirstName { set; get; }
public string LastName { set; get; }
public bool sex { get; set; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<Person> classes1 = new List<Person>();
classes1.Add(new Person() { FirstName = "Kim", LastName = "Tom", sex = true });
classes1.Add(new Person() { FirstName = "Kim", LastName = "Tom1", sex = true });
classes1.Add(new Person() { FirstName = "Kim", LastName = "Tom2", sex = true });
classes1.Add(new Person() { FirstName = "Kim", LastName = "Tom3", sex = true });
classes1.Add(new Person() { FirstName = "Kim", LastName = "Tom4", sex = true });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry", sex = false });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry1", sex = false });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry2", sex = false });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry3", sex = false });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry4", sex = false });
classes1.Add(new Person() { FirstName = "Kyo", LastName = "Jerry5", sex = false });
var childern = from child in classes1.Where<Person>(p => p.GetType().GetProperty("FirstName").GetValue(p, null).ToString() == "Kim") select child;
foreach (Person p in childern)
{
MessageBox.Show(p.LastName);
}
}
我试验了下 貌似没有问题啊, 对linq 不熟,感觉你的问题还是出在数据的结构上, 再仔细看看吧 哈哈
------解决方案--------------------
如果字段太多,建议你先做一个Dictionary来确定Lambda表达式
例子:
public class PeopleCntorl
{
public Dictionary<string, IEnumerable<people>> Dic;
public PeopleCntorl()
{
List<people> peoples = new List<people>()
{
new people{ID=0, Name="Rose", Age=21 },
new people{ID=1, Name="Jack", Age=23 },
new people{ID=2,Name="Mike",Age=29}
};
Dic = new Dictionary<string, IEnumerable<people>>();
IEnumerable<people> people=from x in peoples
select x.Name;
IEnumerable<people> people2 = from x in peoples
select x.Age;
Dic.Add("1", people);
Dic.Add("2", people2);
}
public IEnumerable<people> GetEnumerable(string name)
{
IEnumerable<people> iEnumerale=Dic[name];