这是我写的一些代码。变量aa具有一组不明显的值。我想aa是一组不同的值,所以我需要一个“分组”。我遇到的问题是“new”变量是一个动态创建的字符串,在完成新的操作之前我无法对其进行分组。
List<KeyValuePair<String, int>> x = new List<KeyValuePair<string, int>>();
x.Add(new KeyValuePair<String, int>("one", 1));
x.Add(new KeyValuePair<String, int>("two", 2));
List<KeyValuePair<String, int>> y = new List<KeyValuePair<string, int>>();
y.Add(new KeyValuePair<String, int>("one", 1));
y.Add(new KeyValuePair<String, int>("xxx", 12));
var aa = from xx in x
from yy in y
select new { AA = string.Format("a={0}, b={1}", xx, yy) };
答案 0 :(得分:0)
可以使用Distinct()
//This var can be exchanged with IEnumerable<string>
var aa = (from xx in x
from yy in y
select string.Format("a={0}, b={1}", xx, yy))
.Distinct();
如果你想让列表x的内容在y上排除,或者你的内容在x上独占,你就拥有Except()
var aa1 = from xx in x
from yy in y
select new { AA = string.Format("a={0}, b={1}", xx, yy) };
/*RESULT:
a=[one, 1], b=[one, 1]
a=[one, 1], b=[xxx, 12]
a=[two, 2], b=[one, 1]
a=[two, 2], b=[xxx, 12]*/
var aa2 = from xx in x
from yy in y.Except(x)
select new { AA = string.Format("a={0}, b={1}", xx, yy) };
/*RESULT:
a=[one, 1], b=[xxx, 12]
a=[two, 2], b=[xxx, 12]*/
var aa3 = from xx in x.Except(y)
from yy in y
select new { AA = string.Format("a={0}, b={1}", xx, yy) };
/*RESULT:
a=[two, 2], b=[one, 1]
a=[two, 2], b=[xxx, 12]*/
var aa4 = from xx in x.Except(y)
from yy in y.Except(x)
select new { AA = string.Format("a={0}, b={1}", xx, yy) };
/*RESULT:
a=[two, 2], b=[xxx, 12]*/
答案 1 :(得分:0)
是的,你可以用aa.ToList()实现,然后分组。但你至少应该说出你期望的输出