有人可以解释我如何使用b
var a = Function.call.bind(b, null);
function b(){
//do some stuff
}
来解决此问题:
GroupBy
这一个:Select
其中:
public class BadClass{
public int id; //can be grouped by id
public string name; //identical for the same Id
public bool flag; //identical for the same Id
public int bId;
public string bName;
public int cId;
public string cName;
}
我在BadClass中创建数据示例:
List <A>
我尝试做出类似的事情:
public class A {
public int id;
public string name;
public bool flag;
public List<B> bList;
}
public class B {
public int id;
public string name;
public C c;
}
public class C {
public int id;
public int name;
}
但不知道如何做对。
更新
List<BadClass> badClass = new List<BadClass>() {
new BadClass(){ id = 1, name = "A1", flag = true, bId = 1, bName = "B1", cId = 1, cName = "C1" },
new BadClass(){ id = 1, name = "A1", flag = true, bId = 2, bName = "B2", cId = 3, cName = "C2" },
new BadClass(){ id = 1, name = "A1", flag = true, bId = 3, bName = "B3", cId = 1, cName = "C1" },
new BadClass(){ id = 2, name = "A2", flag = false, bId = 4, bName = "B4", cId = 2, cName = "C2" },
new BadClass(){ id = 2, name = "A2", flag = false, bId = 5, bName = "B5", cId = 3, cName = "C3" }
};
/*
+----+------+-------+-----+-------+-----+-------+
| id | name | flag | bId | bName | cId | cName |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 1 | B1 | 1 | C1 |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 2 | B2 | 1 | C1 |
+----+------+-------+-----+-------+-----+-------+
| 1 | A1 | true | 3 | B3 | 3 | C3 |
+----+------+-------+-----+-------+-----+-------+
| 2 | A2 | false | 4 | B4 | 2 | C2 |
+----+------+-------+-----+-------+-----+-------+
| 2 | A2 | false | 5 | B5 | 3 | C3 |
+----+------+-------+-----+-------+-----+-------+
*/
这是var result = badClass.GroupBy(x => x.id).Select(x => x. ???? ) ???? =(
中的错误我需要将名称var result = badClass
.GroupBy(x => x.id)
.Select(x => new A {
id = x.Key,
name = x.First().name,
flag = x.First().flag,
bList = x.ToList()
});
更改为bList = x.ToList();
e.t.c。
解答:
bId
答案 0 :(得分:3)
只需添加一个.Select和ToList,它将包含您需要的所有项目
var result = badClass.GroupBy(x => x.id).Select(x => x.ToList());
答案 1 :(得分:1)
var result = badClass
.GroupBy(x => x.id)
.Select(x => new A
{
id = x.Key,
name = x.First().name,
flag = x.First().flag,
bList = badClass.Where(y => y.id == x.Key).Select(y =>
new B { id = y.bId, name = y.bName, c = new C { id = y.cId, name = y.cName } }).ToList()
});
这可以让你得到你想要的东西
但说实话,我更倾向于使用foreach
循环+ Dictionary
来提高可读性。