Linq自我加入

时间:2017-10-31 14:04:39

标签: c# linq

我有一个功能

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int type { get; set; }
}

List<Employee> GetData()
{
    var emp1 = new Employee() { Id = 1, Name = "A1", type = 1};
    var emp3 = new Employee() { Id = 1, Name = "A3", type = 2};
    var emp2 = new Employee() { Id = 1, Name = "A2", type = 3};
    var emp4 = new Employee() { Id = 2, Name = "A4", type = 1};
    var emp5 = new Employee() { Id = 2, Name = "A5", type = 2};
    var emp6 = new Employee() { Id = 2, Name = "A6", type = 3};

    var empList = new List<Employee>() { emp1, emp2, emp3, emp4, emp5, emp6 };
    return empList;
}

然后我有一个函数将被调用来过滤数据

public class KeyVal
{
    public int Type { get; set; }
    public string Value { get; set; }
}

public void filterData(KeyVal keyVal1, KeyVal keyVal2)
{
    //keyVal1 = {Type = 1, Vlaue = "A1"}
    //keyVal1 = {Type = 2, Vlaue = "A2"}

    var empList = GetData();
    //Some linq
}

我希望结果能够这样, 我想在Id基础上对数据进行分组

Id     Value
 1   Name: "A1", Type: 1
     Name: "A3", Type: 2
     Name: "A2", Type: 3
 2   Name: "A4", Type: 1
     Name: "A5", Type: 2
     Name: "A6", Type: 3

并基于输入'KeyVal keyVal1, KeyVal keyVal2' 如果同一组匹配中的键和值返回该对象。 即

keyVal1 = {1 , "A1"}
keyVal2 = {3 , "A2"}

它应该返回第1组

1 个答案:

答案 0 :(得分:1)

您希望按<div>对结果进行分组,然后预测Id

KeyVal

或使用查询语法:

var result = empList.GroupBy(key => key.Id, val => new KeyVal(val.type, val.name));

给定类型var result = from item in empList group new KeyVal(item.type, item.Name) by item.Id into g select new { Id = g.Key, Value = g.ToList() }; 的使用输入以查找匹配组:

KeyVal

如果您覆盖var group = result.FirstOrDefault(g => g.Any(item => item.Type == input.Type && item.Value == input.Value)); Equals,则可以:

GetHashCode

对于两个对象作为用户输入:

var group = result.FirstOrDefault(g => g.Contains(input));

对于大量数据,您可以将嵌套集合投影为var group = result.FirstOrDefault(g => g.Contains(input1) && g.Contains(input2)); ,然后HashSet<KeyVal>将位于Contains而非O(1)将其从总计中删除O(n)O(n^2)(不计算分组操作的时间。