简体   繁体   中英

How to access the member of an IGrouping?

The two lines below return an IGrouping<string, DataRow> :

var mbVals = GetMBValues_MBvsPU(mbRptDataPkg);
var puVals = GetPUValues_MBvsPU(puRptDataPkg);

I'd though that you could access the grouping's data like this mbVals[StringKey] but that doesn't look possible. I can do a foreach over the DataRows but it just seems to me one should be able to easily access through a linq expression somehow.

What I'd like to do is compare fields in the datarows from one with fields from datarows of the other through the keys.

Any thoughts?

Thanks!

IGrouping<> is IEnumerable<> so you use the ElementAt() extension method.

But for the situation you describe, you may be better off using Zip() to unify the two groups (if the items are in the same order and match exactly) or using Join() if they don't.

An instance that implements IGrouping<T, U> has a (one) key of type T . Since you want to compare based on keys (plural), an IGrouping<string, DataRow> isn't what you need.

You need an IEnumerable<IGrouping<string, DataRow>> or an ILookup<string, DataRow> . Something that has many keys.

ILookup<string, DataRow> source1 = GetSource1();
ILookup<string, DataRow> source2 = GetSource2();

var BothKeyed = 
(
 from key in source1.Select(g => g.Key).Union(source2.Select(g => g.Key))
 select new
 {
   Key = key,
   In1 = source1[key],//note, In1 may be empty.
   In2 = source2[key] //note, In2 may be empty.
 }
).ToLookup(x => x.Key);

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