开发者

Converting some Excel formula to C#

I'm trying to convert some Excel formulas into C# code, and I'm kind of lost...

I have the following:

SUMPRODUCT(1*(RIGHT(A1)={"a","e","i","n","y"}))

What exactly does that mean?

Here is what I know:

  • RIGHT(A1) returns the last character of the text in A1.
  • SUMPRODUCT({1,2,3}, {4,5,6}) returns 1*4 + 2*5 + 3*6 (something like a scalar product, right?)

b开发者_如何学Pythonut here is what I don't understand:

If the text is Claude, for example...

RIGHT(A1)={"e","a","b","c","d"} returns TRUE

and

RIGHT(A1)={"a","b","e","c","d"} returns FALSE

I only changed the index position of the e character.

What is happening there?

What I'm not understanding?


Basically the formula is checking if the last character in cell A1 is any of the following characters: a, e, i, n, or y. The SUMPRODUCT part is important because it is a hack to check the entire array at once against the last character. When you strip that part out and just use RIGHT(A1)={"a","b","e","c","d"}, Excel actually only looks at the first entry in the array, checks to see if it's a match, and returns immediately. So when 'e' is in the first position, you get True.

SUMPRODUCT allows the checking to be applied across the entire array. Another way to see this would be to manually type it out into separate cells in a grid fashion like this

       A   |       B      |  C  |      D
1 | Claude | =RIGHT(A1,1) | 'a' | =1*(B1=C1)
2 |        | =RIGHT(A1,1) | 'e' | =1*(B2=C2)
3 |        | =RIGHT(A1,1) | 'i' | =1*(B3=C3)
4 |        | =RIGHT(A1,1) | 'n' | =1*(B4=C4)
5 |        | =RIGHT(A1,1) | 'y' | =1*(B5=C5)
6 |        |              |     | =SUM(D1:D5)

The bottom right cell would contain a 1 if any of the characters a,e,i,n,y are at the end of the value in A1, or a 0 if not. I am manually performing the same logic as SUMPRODUCT to get to the same result.

So, how this would be accomplished in C#.Net:

var checkValue = "Claude";
var letters = {"a", "e", "i", "n", "y"};
var found = 0;

foreach (var theLetter in letters)
    if (checkValue.EndsWith(theLetter))
        found = 1;

return found; // returns same value as Excel function


If you want one line based on @CoryLarson's suggestion that will work for any set of letters:

Func<string, string[], int> LetterCount = (x, y) => y.Contains(x.Substring(x.Length-1, 1)) ? 1 : 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜