我有一个包含3条记录的集合:
Add=A1,A2,A3
Division=D1,D2,D3
Multiply=M1,M2,M3,A2
type=Add,Div,Multiply
names=A1,A2 etc...
现在,我希望将Add
和Multiply
的所有唯一名称添加到单个变量中
并且只有单独变量中的分区名称列表:
预期产出:
CombineList=A1,A2,A3,M1,M2,M3
DivisionList=D1,D2,D3
这是我的疑问:
var TypesList = Ds1.Tables["dtSubVariant"].Rows.Cast<DataRow>()
.GroupBy(r => r["Type"] + "")
.Where(g => activeTypes.Contains(g.Key))
.Select(g => new {
type = g.Key,
names = g.ToList()
}).ToList();
var result = new
{
CombineList = (from t in TypesList
where t.type != "Division"
let name=t.names.Distinct()
select new
{
names=name
}).ToList(),
DivisionList = TypesList.Where(t => t.method == "Division")
.Select(t=>t.names).ToList()
};
但我仍然在Combine list
获得2个列表,如下所示:
[0]:Add
A1,A2,A3
[1]:
Multiple
M1,M2,M3,A2
答案 0 :(得分:2)
在更好地理解学习需要之后,以下是答案。
您想要在notification
中对记录进行分组(在此示例中 - 在您的代码中为rows
)
通过我创建的Ds1.Tables["dtSubVariant"].Rows.Cast<DataRow>()
列表之类的东西。然后,您希望拥有每个组的所有内部集合的不同值:
grouping
如果您需要List<dynamic> rows = new List<dynamic>
{
new { Type = "Add", Values = new []{"A1","A2", "A3"} },
new { Type = "Division", Values = new []{"D1","D2", "D3"} },
new { Type = "Multiply", Values = new []{"M1","M2","M3","A1"} }
};
List<dynamic> grouping = new List<dynamic>
{
new { Type = "CombinedList", Types = new [] {"Add", "Multiply"} },
new { Type = "Division", Types = new [] {"Division"} }
};
var result = (from r in rows
from g in grouping
where ((IEnumerable<string>)(g.Types)).Contains((string)r.Type)
group r by g.Type into rg
select new
{
Type = rg.Key,
Values = rg.SelectMany(item => (string[])item.Values).Distinct().ToList()
}).ToList();
和Add
的明确列表,请使用Multiply
Union
可以使用List<string> Add = new List<string> { "A1", "A2", "A3" };
List<string> Multiply = new List<string> { "M1", "M2", "M3", "A2" };
var result = Add.Union(Multiply).ToList();
但只是添加将两个列表放在一起而不删除重复项
在上面的代码的上下文中,您的问题是Concat
中的每个项目都有一个内部集合 - 并且您希望所有这些内部集合的合并是不同的。使用TypesList
和SelectMany
:
Distinct
所有在一起:
var combineList = TypesList.Where(t => t.type == "Add" || t.type == "Multiply")
.SelectMany(t => t.names)
.Distinct();
答案 1 :(得分:1)
var result = new
{
CombineList = TypesList.Where( t => t.type == "Add")
.Union(TypesList.Where( t => t.type == "Multiply"))
.Select(a => new { names = a.name }),
DivisionList = TypesList.Where(t => t.method == "Division").Select(t=>t.names).ToList()
};
您可以打印输出
Console.Write("CombineList");
foreach( var item in result.CombineList)
{
Console.Write(item.name + " ");
}
Console.WriteLine("");
Console.Write("DivisionList");
foreach( var item in TypesList.Where( t => t.type == "Division"))
{
Console.Write(item.name + " ");
}