简体   繁体   中英

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. I would like for aa to be a set of distinct values so I need a "group by". 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.

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()

//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()

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. But you should at least say what do you expect as output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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