使用Linq Dynamic分组
本文关键字:分组 Dynamic Linq 使用 | 更新日期: 2023-09-27 18:22:33
我想对从下拉列表中选择的值进行分组,但该值可以是DateTime或String,并且我只想提供一种情况。你有这个主意吗?
我的代码:
public class Personne
{
public String _NOM { get; set; }
public DateTime _DDN { get; set; }
public String _VILLE { get; set; }
public Personne(String nom, DateTime ddn, String ville)
{
this._NOM = nom;
this._DDN = ddn;
this._VILLE = ville;
}
}
这里是按钮点击事件:
List<Personne> _liste = new List<Personne>();
_liste.Add(new Personne("toto", new DateTime(1993, 3, 23), "Paris"));
_liste.Add(new Personne("tata", new DateTime(1993, 3, 23), "New-York"));
_liste.Add(new Personne("titi", new DateTime(1987, 2, 10), "Paris"));
var qry = _liste.AsQueryable().OrderBy(listeCritere.SelectedValue)
.GroupBy(listeCritere.SelectedValue, "It", null);
if (listeCritere.SelectedValue == "_DDN")
{
foreach (IGrouping<DateTime, Personne> item in qry)
{
Response.Write(item.Key + "<br/>");
foreach (Personne p in item)
{
Response.Write(" Nom complet : " + p._NOM + "<br/>");
}
}
}
else
{
foreach (IGrouping<String, Personne> item in qry)
{
Response.Write(item.Key + "<br/>");
foreach (Personne p in item)
{
Response.Write(" Nom complet : " + p._NOM + "<br/>");
}
}
}
您可以在IEnumerable<Personne>
上循环,然后在循环中获得正确的密钥类型:
var qry = _liste.AsQueryable().OrderBy(listeCritere.SelectedValue)
.GroupBy(listeCritere.SelectedValue, "It", null);
foreach (IEnumerable<Personne> item in qry)
{
if (item is IGrouping<DateTime, Personne>)
Response.Write(((IGrouping<DateTime, Personne>)item).Key + "<br/>");
else if (item is IGrouping<object, Personne>)
Response.Write(((IGrouping<object, Personne>)item).Key + "<br/>");
foreach (Personne p in item)
{
Response.Write(" Nom complet : " + p._NOM + "<br/>");
}
}
您也可以将循环移动到一个通用函数:
public void ButtonClickHandler(object sender, EventArgs e)
{
var qry = _liste.AsQueryable().OrderBy(listeCritere.SelectedValue)
.GroupBy(listeCritere.SelectedValue, "It", null);
if (listeCritere.SelectedValue == "_DDN")
WritePersonneResponse<DateTime>(Response, qry);
else
WritePersonneResponse<string>(Response, qry);
}
public void WritePersonneResponse<T>(HttpResponse response, IQueryable qry)
{
foreach (IGrouping<T, Personne> item in qry)
{
response.Write(item.Key + "<br/>");
foreach (Personne p in item)
{
response.Write(" Nom complet : " + p._NOM + "<br/>");
}
}
}
在linq中,您可以在闭包中生成函数——这里我们只生成一个函数来返回键值(但始终为字符串):
string gby = "NOM";
//string gby = "DDN";
//string gby = "VILLE";
var qry = _liste
.GroupBy(x => {
string result = "";
switch (gby)
{
case "NOM": result = x._NOM; break;
case "DDN" : result = x._DDN.ToString(); break;
case "VILLE" : result = x._VILLE ; break;
}
return result;
}
).ToList();