LINQ Select Distinct While Evaluating Multiple Rows
I have an EnumerableRowCollection that looks like the following:
VendorCode | GroupType | Variance
01165 G .16
01165 G .16
01165 CH .16
01165 CH .18
07754 G .25
07754 G .25
07754 G .39
Essentially, this is a massive list of vendor codes, their groups, and price variances. I need to compose a query that will create a distinct list vendor codes and group types. The catch, however, is that I need to evaluate all of the variances associated with that particular VendorCode/GroupType to see if they are all the same - it they are not, I need to return some way of signifying that the group has a "custo开发者_运维知识库m" variance, otherwise it needs to return the value (ie: if they are all .16, then return .16, if there are multiple values, return "custom")
The result would look like this, based off of the list I showed above.
VendorCode | GroupType | Variance
01165 G .16
01165 CH custom
07754 G custom
I have no trouble getting a distinct list of VendorCode/GroupType - this is what I have so far:
Dim distinctList = From q In query Select q.VendorCode, q.GroupType, (evaluated q.Variance here?) Distinct
(where "query" is an EnumerableRowCollection(Of (anonymous type)))
I'm at a loss, though, on how to evaluate the variance property to get the result that I need - any ideas?
I can't do the VB, but in C# I think you'd want something like:
var query = from item in source
group item by new { item.VendorCode, item.GroupType } into g
select new { g.Key.VendorCode,
g.Key.GroupType,
Variance = ComputeVariance(g) };
...
string ComputeVariance(IEnumerable<YourItemType> group)
{
var distinctVariance = group.Select(x => x.Variance)
.Distinct();
using (var iterator = distinctVariance.GetEnumerator())
{
iterator.MoveNext(); // Assume this will return true...
var first = iterator.Current;
return iterator.MoveNext() ? "custom" : first.ToString();
}
}
That's assuming you're using LINQ to Objects. If you need to do this in LINQ to SQL etc, I'd take a slightly different approach.
精彩评论