简体   繁体   English

如何在LINQ中按新字符串分组

[英]How to group by a new string in LINQ

Here is some code I have written. 这是我写的一些代码。 The variable aa has a set of values that are not distinct. 变量aa具有一组不同的值。 I would like for aa to be a set of distinct values so I need a "group by". 我希望aa是一组不同的值,所以我需要一个“分组依据”。 The problem I have is that the "new" variable is a string created on the fly and I cannot group by it before I have done the new. 我的问题是“ 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) };

Could use Distinct() 可以使用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();

if you want to make list x's content excusive over y and or y's content exclusive over x the you have the command Except() 如果要使列表x的内容对y有意义,或者要使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]*/

Yes you can you can materialize with aa.ToList() and then group by. 是的,您可以使用aa.ToList()实现,然后分组。 But you should at least say what do you expect as output 但是您至少应该说出您期望输出什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM