日期:2014-05-20  浏览次数:20772 次

Linq to entity如何动态的根据任一字段进行排序?
如题,我想用Linq查询数据,并根据前台传过来的Entity的一个属性进行排序。

  例如:
  Student类有Name和Age,前台将属性名(name或age)传到后台,如何组装Linq?


  还有一个问题是我想用获得对象某个属性在数据库中的不同的值,distinct怎么用,属性是动态的,也是接受对象的属性名来完成操作。

------解决方案--------------------
C# code

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];