试试这个:
简单类:
class Foo
{
public string ServerName { get; set; }
public string UserName { get; set; }
public string LearningGroup { get; set; }
}
样本数据的初始化:
List<Foo> _source = new List<Foo>
{
new Foo { ServerName ="ServA", UserName = "John", LearningGroup ="First Group" },
new Foo { ServerName ="ServA", UserName = "Kate", LearningGroup ="First Group" },
new Foo { ServerName ="ServA", UserName = "John" },
new Foo { ServerName ="ServB", UserName = "Kate", },
new Foo { ServerName ="ServB", UserName = "Kate", LearningGroup ="Second Group" }
};
查询解决问题:
var tmp = (from x in _source
join f in _source on new { UserName = x.UserName, ServerName = x.ServerName } equals new { UserName = f.UserName, ServerName = f.ServerName }
where !string.IsNullOrEmpty(x.LearningGroup)
select x).Distinct();
数据表解决方案:
DataTable dt = new DataTable();
dt.Columns.Add("ServerName", typeof(string));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("LearningGroup", typeof(string));
dt.Rows.Add("ServA", "John", "First Group");
dt.Rows.Add("ServA", "Kate", "First Group");
dt.Rows.Add("ServA", "John", null);
dt.Rows.Add("ServB", "Kate", null);
dt.Rows.Add("ServB", "Kate", "Second Group");
var tmpDT = (from x in dt.AsEnumerable()
join f in dt.AsEnumerable() on new { UserName = x.Field<String>("UserName"), ServerName = x.Field<String>("ServerName") } equals new { UserName = f.Field<String>("UserName"), ServerName = f.Field<String>("ServerName") }
where !string.IsNullOrEmpty(x.Field<String>("LearningGroup"))
select x).Distinct();
这个查询的结果类型是IEnumerable<DataRow>
这样的,你可以使用 foreach 循环来创建新DataTable
的具有适当数据的:
DataTable newDT = new DataTable();
newDT.Columns.Add("ServerName", typeof(string));
newDT.Columns.Add("UserName", typeof(string));
newDT.Columns.Add("LearningGroup", typeof(string));
foreach (var item in tmpDT)
{
newDT.ImportRow(item);
}