问题描述:

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) };

网友答案:

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

网友答案:

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]*/
相关阅读:
Top