Reputation: 71
How to convert this sample foreach into lambda expression?
foreach (ADOMD.Member iMember in pMemberCollection)
{
decimal lDimensionValue = 0;
if (Decimal.TryParse(iMember.Name, out lDimensionValue))
lDimensionValues.Add(lDimensionValue);
}
lDimensionValues.Sort();
ADOMD.Member is a interface looks like
[TypeLibType(xxx)]
[Guid("xxxxx")]
public interface Member
{
[DispId(0)]
string Caption { get; }
[DispId(1610743817)]
int ChildCount { get; }
string Name { get; }
[DispId(1610743812)]
Member Parent { get; }
[DispId(1610743819)]
bool ParentSameAsPrev { get; }
[DispId(1610743815)]
}
Upvotes: 1
Views: 108
Reputation: 3429
Had to try to do this in as few lines as possible, interesting problem, i would not convert your method to LINQ though, if it already works (what works works)
lDimensionValues = pMemberCollection.Where(a => {
decimal lDimensionValued;
return decimal.TryParse(a.Name, out lDimensionValued);
}).Select(a=> decimal.Parse(a.Name)).Sort();
Upvotes: 0
Reputation: 171178
lDimensionValues =
pMemberCollection
.Cast<ADOMD.Member>()
.Select(iMember => {
decimal lDimensionValue = 0;
if (Decimal.TryParse(iMember.Name, out lDimensionValue))
return (decimal?)lDimensionValue;
else return null;
})
.Where(x => x != null)
.Select(x => x.Value)
.OrderBy(x => x)
.ToList();
Very ugly and verbose. If we had a TryParseDecimal
method it would be cleaner.
This is not a perfect case for LINQ. Among other reasons due to the legacy collection that requires a Cast
apparently.
Upvotes: 4