Last active
June 13, 2024 14:26
-
-
Save KOZ60/724278ffb5c24625afed22ea9c451381 to your computer and use it in GitHub Desktop.
XLColumn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
public class XLColumn : IEquatable<XLColumn> | |
{ | |
private const string mask = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
private readonly int columnIndex; | |
public XLColumn(int value) { | |
columnIndex = value; | |
} | |
public XLColumn(string value) { | |
columnIndex = GetInteger(value); | |
} | |
public override bool Equals(object obj) { | |
var other = obj as XLColumn; | |
if (other == null) { | |
return Equals(other); | |
} | |
return false; | |
} | |
public bool Equals(XLColumn other) => Equals(this, other); | |
public override int GetHashCode() => columnIndex; | |
public override string ToString() => GetString(columnIndex); | |
public static bool Equals(XLColumn a, XLColumn b) { | |
// Boxing to prevent infinite loops with implicit conversion | |
object oa = a; | |
object ob = b; | |
if (ReferenceEquals(oa, ob)) { | |
return true; | |
} | |
if (oa == null || ob == null) { | |
return false; | |
} | |
return a.columnIndex == b.columnIndex; | |
} | |
public static bool operator ==(XLColumn a, XLColumn b) => Equals(a, b); | |
public static bool operator !=(XLColumn a, XLColumn b) => !Equals(a, b); | |
public static int operator +(XLColumn a, XLColumn b) => a.columnIndex + b.columnIndex; | |
public static int operator -(XLColumn a, XLColumn b) => a.columnIndex - b.columnIndex; | |
private static int GetInteger(string str) { | |
if (str == null) { | |
return 0; | |
} | |
int baseValue = 1; | |
int intValue = 0; | |
for (int i = str.Length - 1; i >= 0; i--) { | |
char c = str[i]; | |
int index = mask.IndexOf(c); | |
if (index == -1) { | |
throw new ArgumentOutOfRangeException(); | |
} | |
intValue += (index + 1) * baseValue; | |
baseValue *= mask.Length; | |
} | |
return intValue; | |
} | |
private static string GetString(int value) { | |
if (value < 0) { | |
throw new ArgumentOutOfRangeException(); | |
} | |
int baseValue = mask.Length; | |
var sb = new StringBuilder(); | |
while (value > 0) { | |
int tmp = (value - 1) / baseValue; | |
int index = value - tmp * baseValue; | |
char c = mask[index - 1]; | |
sb.Insert(0, c); | |
value = tmp; | |
} | |
return sb.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment