This works the way I want, but seems a lot of duplication and probably takes way longer than it needs to:
/*QA */
var providerIds = new[] { "315276" ,"145479" ,"455731" };
/**/
// match providers with customers by phone number ///////////////////////////////////////
var matches = ( from p in ProviderInfo
from r in TM99R.RM00101s.Where(
r =>
( p.PHONE.Substring( 0 ,10 ) == r.PHONE1.Substring( 0 ,10 )
|| p.PHONE.Substring( 0 ,10 ) == r.PHONE2.Substring( 0 ,10 )
|| p.PHONE.Substring( 0 ,10 ) == r.PHONE3.Substring( 0 ,10 ) )
)
/* QA */
where providerIds.Contains( p.Provnum )
orderby p.Provnum
/**/
select new {
actualPhone = p.PHONE.Substring( 0 ,10 )
,p.Provnum
,r.CUSTNMBR
}
);
// group results ///////////////////////////////////////
var providers = ( from p in matches
/* QA */
where providerIds.Contains( p.Provnum )
orderby p.Provnum
/**/
group p by new{
p.Provnum,
p.actualPhone
} into g
select new{
Provnum = g.Key.Provnum
,Phone = g.Key.actualPhone
,CustomerCount = g.Count()
// compile multiple customer numbers in to one string
,CustomerList = (
from cl in matches
where cl.actualPhone == g.Key.actualPhone
orderby cl.CUSTNMBR.Length
select new { cl.CUSTNMBR }
).ToList()
// select shortest CUSTNMBR string
,PrimaryCustomerNumber = (
from cl in matches
where cl.actualPhone == g.Key.actualPhone
orderby cl.CUSTNMBR.Length
select new { cl.CUSTNMBR }
).ToList().First()
}
);