DataTable或者List 中的数据是:
Company CaseNum
中国台湾 0001
中国台湾 0002
中国台湾 0002
香港 0001
香港 0001
要求结果:
Company Totala Totalb
中国台湾 3 2
香港 2 1
注:按company分组,取得组数(Totala),然后再按company+CaseNum分组,取得组数(Totalb)
这是从网上看到了一组数据, 通过对文章的了解,自己写了一个算法,虽然可以跟原作者相差不大,但是还是要写一下。
public partial class LinqDistinct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List
lit=GetList();
var jlit=from x in lit group x by x.Company into y
select new ComLay { ComName = y.Key, ATotal = y.Count(),BTotal=y.Distinct(new ComInfoComparer()).Count()};
GridView1.DataSource = jlit;
GridView1.DataBind();
}
public List
GetList()
{
List
lt=new List
();
ComInfo cinfo=new ComInfo();
cinfo.Company="中国台湾";
cinfo.CaseNum="0001";
lt.Add(cinfo);
cinfo = new ComInfo();
cinfo.Company="中国台湾";
cinfo.CaseNum="0002";
lt.Add(cinfo);
cinfo = new ComInfo();
cinfo.Company="中国台湾";
cinfo.CaseNum="0002";
lt.Add(cinfo);
cinfo = new ComInfo();
cinfo.Company="香港";
cinfo.CaseNum="0001";
lt.Add(cinfo);
cinfo = new ComInfo();
cinfo.Company="香港";
cinfo.CaseNum="0001";
lt.Add(cinfo);
return lt;
}
}
public class ComLay
{
public string ComName
{
get;
set;
}
public int ATotal
{
get;
set;
}
public int BTotal
{
get;
set;
}
}
public class ComInfo
{
public string Company
{
get;
set;
}
public string CaseNum
{
get;
set;
}
}
public class ComInfoComparer : IEqualityComparer
{
#region IEqualityComparer
Members
bool IEqualityComparer
.Equals(ComInfo x, ComInfo y)
{
if (x.CaseNum.Equals(y.CaseNum) && x.Company.Equals(y.Company))
return true;
return false;
}
int IEqualityComparer
.GetHashCode(ComInfo obj)
{
return (obj.CaseNum + obj.Company).GetHashCode();
}
#endregion
}
通过ComInfoComparer ,可以按照类来进行Distinct