How get range of numbers [duplicate] - c#

This question already has answers here:
Is there a C# type for representing an integer Range?
(10 answers)
Closed 8 years ago.
I have a interval of number [1, 20].
I want a method which returns me range of number available if I decide to ban range [15, 18]. My method should return me a list containing [1,15] and [18, 20]
Range object could looks like something like that
public class Range
{
int Start {get;set;}
int End {get;set;}
}
Any help would be appreciated.

What about this?
IEnumerable<int> range = Enumerable.Range(1, 20);
IEnumerable<int> banned = Enumerable.Range(15, 4);
return range.Except(banned);
The Enumerable class already has a static method which will return a range of values for you - might be simpler to just use those semantics.

This is one of the ways:
static void Main(string[] args)
{
int[] allNumbers = Enumerable.Range(1, 20).ToArray();
GetNumbers(ref allNumbers, new int[] { 16, 17 });
}
private static void GetNumbers(ref int[] nums, int[]exclude)
{
List<int> numsToExlucde =new List<int>();
numsToExlucde.InsertRange(0, exclude);
nums = nums.Where(w => !numsToExlucde.Contains(w)).ToArray();
}

You have four possible cases. The method could look like this (I assume that range contain integer numbers only):
public class Range
{
public int Start { get; set; }
public int End { get; set; }
public IList<Range> Exclude(Range r)
{
if (r.Start <= Start && r.End < End)
{
return new List<Range>{new Range { Start = r.End + 1, End = End }};
}
else if (r.Start > Start && r.End >= End)
{
return new List<Range>{new Range { Start = Start, End = r.Start - 1 }};
}
else if (r.Start > Start && r.End < End)
{
return new List<Range>
{
new Range { Start = Start, End = r.Start - 1 },
new Range { Start = r.End + 1, End = End }
};
}
return new List<Range>();
}
}
// ...
static void Main(string[] args)
{
Range r = new Range { Start = 1, End = 20};
var list = r.Exclude(new Range{ Start = 1, End = 2} );
}

This can help you remove a range from another, or from a set of ranges:
public class Range {
public int Start { get; private set; }
public int End { get; private set; }
public Range(int start, int end) {
Start = start;
End = end;
}
public IEnumerable<Range> RemoveFrom(Range range) {
return RemoveFrom(new Range[] { range });
}
public IEnumerable<Range> RemoveFrom(IEnumerable<Range> items) {
foreach (Range item in items) {
if (End >= item.Start && Start <= item.End) {
if (item.Start <= Start) {
yield return new Range(item.Start, Start);
}
if (item.End >= End) {
yield return new Range(End, item.End);
}
} else {
yield return item;
}
}
}
}
Example:
Range range = new Range(1, 20);
foreach (Range r in new Range(15,18).RemoveFrom(range)) {
Console.WriteLine("{0} - {1}", r.Start, r.End);
}
Output:
1 - 15
18 - 20
Example of removing multiple ranges from other ranges:
Range[] items = new Range[] { new Range(1, 100), new Range(200, 300) };
Range[] exclude = new Range[] { new Range(25, 75), new Range(250, 280), new Range(90, 210) };
foreach (Range r in exclude) {
items = r.RemoveFrom(items).ToArray();
}
foreach (Range r in items) {
Console.WriteLine("{0} - {1}", r.Start, r.End);
}
Output:
1 - 25
75 - 90
210 - 250
280 - 300

You need to traverse through the banned ranges and iteratively create the valid ranges while doing so.
public List<Range> getValidRanges(Range total, List<Range> banned)
{
List<Range> valid = new ArrayList<Range>();
int start = total.getStartTime();
for(Range range: banned)
{
valid.add(new Range(start,banned.getStart()));
start = banned.getEnd();
}
valid.add(new Range(start,total.getEnd()));
return valid;
}

Related

Join element from array if the array element length is less than 5

I am trying to join the next array element together to single element from array if the element of the array is less than length 4. It should add to the next element index.
Another logic is, if the next consecutive array length is also less then 4 char then it joins the next array element also up to 3 times in total. I want to implement this. It's getting complex for me I am not understand this logic.
This is the code, here it has array on titleList, now we have to use the above logic in this array list.
#foreach (var title in randomtitle)
{
</span>#titleList.ElementAt(title)</span>
}
#code {
[Parameter]
public string theTitle { get; set; }
private string[] titleList = Array.Empty<string>();
protected override void OnParametersSet()
{
if (!string.IsNullOrEmpty(theTitle))
{
titleList = theTitle.Split(" ");
}
}
private Random random = new();
private IEnumerable<int> randomtitle =>
Enumerable.Range(0, titleList.Count() - 1) // { 0, 1, 2, 3 } generate sequence
.OrderBy(x => random.Next()) // { 3, 1, 0, 2 } random shuffle
.Take(2) // { 3, 1 } pick two
.ToList();
}
I think you are looking for a method that does following:
take a collection of strings(like a string[])
iterate each string and check if it's length is greater than or equal 4
if so, everything is fine, take it as it is
if not, append the next to the current string and check their length afterwards
if they are still not greater than or equal 4 append the next one, but max 3 times
Then this should work (not tested well though):
Demo: https://dotnetfiddle.net/2uHREv
static string[] MergeItems(IList<string> all, int minLength, int maxGroupCount)
{
List<string> list = new List<string>(all.Count);
for(int i = 0; i < all.Count; i++)
{
string current = all[i];
if(i == all.Count - 1)
{
list.Add(current);
break;
}
if (current.Length < minLength)
{
for (int ii = 1; ii < maxGroupCount && i + ii < all.Count; ii++)
{
int nextIndex = i + ii;
string next = all[nextIndex];
current = current + next;
if (current.Length >= minLength || ii+1 == maxGroupCount)
{
list.Add(current);
i = nextIndex;
break;
}
}
}
else
{
list.Add(current);
}
}
return list.ToArray();
}

How to get the type of an element from range of numbers in c#?

How to get the type of input data from a range of numbers, combining it with an Enum in c#?
I want to avoid using the if/else, moving it to some kind of range, maybe with using IsDefined?
[Flags]
public enum PaymentCodeTypes
{
Other = 1,
Warranty = 2,
Contract = 4
}
var PaymentCodeType = 0;
if (paymentCode >= 80 && paymentCode <= 89)
{
PaymentCodeType = (int) PaymentCodeTypes.Contract;
}
else if (paymentCode >= 90 && paymentCode <= 99)
{
PaymentCodeType = (int) PaymentCodeTypes.Warranty;
} else
{
PaymentCodeType = (int)PaymentCodeTypes.Other;
}
You can use a switch expression, added in C# 8:
var PaymentCodeType = (int)(paymentCode switch {
var x when x >= 80 && x <= 89 => PaymentCodeTypes.Contract,
var x when x >= 90 && x <= 99 => PaymentCodeTypes.Warranty,
_ => PaymentCodeTypes.Other
});
If you want to make it even shorter, sacrificing maintainability:
var PaymentCodeType = (int)((paymentCode / 10) switch { // only works for ranges in the form of 10x ~ (10x + 9)
8 => PaymentCodeTypes.Contract,
9 => PaymentCodeTypes.Warranty,
_ => PaymentCodeTypes.Other
});
I think this is what you are looking for. You can change the ranges without changing code and would be more compliant with SOLID principles.
[Flags]
public enum PaymentCodeTypes
{
Other = 1,
Warranty = 2,
Contract = 4
}
private class Range {
public Range(int highEnd, int lowEnd, PaymentCodeTypes paymentCodeType)
{
this.highEnd = highEnd;
this.lowEnd = lowEnd;
this.paymentCodeType = paymentCodeType;
}
public int lowEnd { get; private set; }
public int highEnd { get; private set; }
public PaymentCodeTypes paymentCodeType { get; private set; }
}
private readonly List<Range> paymentCodeRanges = new List<Range>
{
new Range(0, 79, PaymentCodeTypes.Other),
new Range(80, 89, PaymentCodeTypes.Contract),
new Range(90, 99, PaymentCodeTypes.Warranty),
new Range(100, Int32.MaxValue, PaymentCodeTypes.Other )
};
public int SetPaymentTypeCode(int paymentCode)
{
var range = paymentCodeRanges.Where(x => paymentCode >= x.lowEnd && paymentCode <= x.highEnd).First();
return (int)range.paymentCodeType;
}

Substract shortest string containing all search criteria

I have a problem to solve where given a string source and a collection of search criteria criteria, the algorithm has to return the shortest possible substring of source that contains all items of criteria.
=================================
UPDATE
The same search criteria might be in the source string multiple
times. In that case, it is required to return the sub-string
containing the particular instance of the search criteria such that
it is the shortest among all possible sub-strings.
The search items can contain spaces in them such as hello world
The order in which the search criteria are found does not matter as long as they are all in the resultant sub-string
==================================
String source = "aaa wwwww fgffsd ththththt sss sgsgsgsghs bfbfb hhh sdfg kkk dhdhtrherhrhrthrthrt ddfhdetehehe kkk wdwd aaa vcvc hhh zxzx sss nbnbn";
List<String> criteria = new List<string> { "kkk", "aaa", "sss", "hhh" };
The input above should return the following substring: kkk wdwd aaa vcvc hhh zxzx sss
Unfortunately, I spent a lot of time trying to write such an algorithm but I couldn't get it just right. Below is the code I have got so far:
public struct Extraction
{
public int Start { get; set; }
public int End { get; set; }
public int Length
{
get
{
var length = this.End - this.Start;
return length;
}
}
public Extraction(int start, int end)
{
this.Start = start;
this.End = end;
}
}
public class TextExtractor
{
private String _source;
private Dictionary<String, List<Int32>> _criteriaIndexes;
private Dictionary<String, int> _entryIndex;
public TextExtractor(String source, List<String> searchCriteria)
{
this._source = source;
this._criteriaIndexes = this.ExtractIndexes(source, searchCriteria);
this._entryIndex = _criteriaIndexes.ToDictionary(x => x.Key, v => 0);
}
public String Extract()
{
List<Extraction> possibleExtractions = new List<Extraction>();
int index = 0;
int min = int.MaxValue;
int max = 0;
bool shouldStop = false;
while (index < _criteriaIndexes.Count && !shouldStop)
{
Boolean compareWithAll = index == _criteriaIndexes.Count - 1;
if (!compareWithAll)
{
var current = _criteriaIndexes.ElementAt(index);
this.CalculateMinMax(current, ref min, ref max);
index++;
}
else
{
var entry = _criteriaIndexes.Last();
while (_entryIndex[entry.Key] < entry.Value.Count)
{
int a = min;
int b = max;
this.CalculateMinMax(entry, ref a, ref b);
_entryIndex[entry.Key]++;
Extraction ext = new Extraction(a, b);
possibleExtractions.Add(ext);
}
int k = index - 1;
while (k >= 0)
{
var prev = _criteriaIndexes.ElementAt(k);
if (prev.Value.Count - 1 > _entryIndex[prev.Key])
{
_entryIndex[prev.Key]++;
break;
}
else
{
k--;
}
}
shouldStop = _criteriaIndexes.All(x => x.Value.Count - 1 <= _entryIndex[x.Key]);
_entryIndex[entry.Key] = 0;
index = 0;
min = int.MaxValue;
max = 0;
}
}
Extraction shortest = possibleExtractions.First(x => x.Length.Equals(possibleExtractions.Min(p => p.Length)));
String result = _source.Substring(shortest.Start, shortest.Length);
return result;
}
private Dictionary<String, List<Int32>> ExtractIndexes(String source, List<String> searchCriteria)
{
Dictionary<String, List<Int32>> result = new Dictionary<string, List<int>>();
foreach (var criteria in searchCriteria)
{
Int32 i = 0;
Int32 startingIndex = 0;
var indexes = new List<int>();
while (i > -1)
{
i = source.IndexOf(criteria, startingIndex);
if (i > -1)
{
startingIndex = i + 1;
indexes.Add(i);
}
}
if (indexes.Any())
{
result.Add(criteria, indexes);
}
}
return result;
}
private void CalculateMinMax(KeyValuePair<String, List<int>> current, ref int min, ref int max)
{
int j = current.Value[_entryIndex[current.Key]];
if (j < min)
{
min = j;
}
int indexPlusWordLength = j + current.Key.Length;
if (indexPlusWordLength > max)
{
max = indexPlusWordLength;
}
}
}
I would appreciate it if someone could point out where did I go wrong in my algorithm. Moreover, I kinda feel this is a very naive implementation. Maybe there is a better approach to solve this problem than trying to try out combinations of indexes?
Thanks!
This is a much simpler algorithm that will give you the shortest substring.
void Main()
{
String source = "aaa wwwww fgffsd ththththt sss ww sgsgsgsghs bfbfb hhh sdfg kkk " +
"dhdhtrherhrhrthrthrt ddfhdetehehe kkk wdwd aaa vcvc hhh zxzx sss ww nbnbn";
List<String> criteria = new List<string> { "kkk", "aaa", "sss ww", "hhh" };
var result = GetAllSubstringContainingCriteria(source, criteria)
.OrderBy(sub => sub.Length).FirstOrDefault();
// result is "kkk wdwd aaa vcvc hhh zxzx sss ww"
}
private IEnumerable<string> GetAllSubstringContainingCriteria(
string source, List<string> criteria)
{
for (int i = 0; i < source.Length; i++)
{
var subString = source.Substring(i);
if (criteria.Any(crit => subString.StartsWith(crit)))
{
var lastWordIndex =
GetLastCharacterIndexFromLastCriteriaInSubstring(subString, criteria);
if (lastWordIndex >= 0)
yield return string.Join(" ", subString.Substring(0, lastWordIndex));
}
else
continue;
}
}
private int GetLastCharacterIndexFromLastCriteriaInSubstring(
string subString, List<string> criteria)
{
var results = criteria.Select(crit => new {
index = subString.IndexOf(crit),
criteria = crit});
return results.All(result => result.index >= 0)
? results.Select(result => result.index + result.criteria.Length).Max()
: -1;
}
Let the Java built-in classes do the work. How about converting your criteria to a regular expression Pattern. If the criteria are X or Y or Z . . ., convert this into a regular expression of the form "(X)|(Y)|(Z)|...", compile it, and execute it against the source string.
This, of course, returns the leftmost match. You could code a very straightforward loop that iterates across all occurrences, caches them, and chooses the shortest--or the leftmost shortest--or, if two or more are equally short, then all of those.

Counting groups of files based on size

How can I simplify this? I am trying to get the count of Excel files from a directory and subdirectories based on their size. I have at least 10 different groupings.
var queryList2Only = from i in di.GetFiles("*.xls", SearchOption.TopDirectoryOnly)
.Where(f => f.Length <= 5120)
select i.Length;
if (queryList2Only.Any())
{
dest.WriteLine("Excel File <= 5 KB");
dest.WriteLine(queryList2Only.Count());
dest.WriteLine("");
}
var queryList3Only = from i in di.GetFiles("*.xls", SearchOption.TopDirectoryOnly)
.Where(f => f.Length > 5120 && f.Length <= 10240)
select i.Length;
if (queryList3Only.Any())
{
dest.WriteLine("Excel File > 5 KB and <= 10 KB");
dest.WriteLine(queryList3Only.Count());
dest.WriteLine("");
EDIT:
I need this
<= 5 KB,> 5 KB and <= 10 KB,> 10 KB and <= 20 KB,> 20 KB and <= 100 KB,> 100 KB and <= 1000 KB,> 1000 KB and <=5 MB,> 5 MB and <=10 MB,> 10 MB and <=20 MB,> 20 MB and <=50 MB,> 50 MB and <=100 MB
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo Folder = new DirectoryInfo(textBox1.Text);
var _logFolderPath4 = Path.Combine(textBox1.Text.Trim(), "log");
if (Folder.Exists)
if (!Directory.Exists(_logFolderPath4))
Directory.CreateDirectory(_logFolderPath4);
DirectoryInfo di = new DirectoryInfo(#"D:\Material\");
bool time = false;
using (var dest = File.AppendText(Path.Combine(_logFolderPath4, "Excel.txt")))
{
if (!time)
{
dest.WriteLine("---------------------" + DateTime.Now + "---------------------");
dest.WriteLine("");
time = true;
}
CountFiles(dest, di, #"*.txt");
}
}
You need to have your ranges in a collection, and enumerate over them.
Here is an example that should get you going - the sizes array contains the steps, of course you should choose the steps that makes sense to your application:
int[] sizes = Enumerable.Range(0,10).Select(n => (int)Math.Pow(2,n + 8)).ToArray();
int lower = 0;
foreach(var size in sizes)
{
var files = di.GetFiles("*.*").Where(f => f.Length >= lower && f.Length < size);
Console.WriteLine("Between {0} and {1} bytes:", lower,size);
foreach(var file in files)
Console.WriteLine("\t{0}",file);
lower = size;
}
You don't necessarily need LINQ for this. It would be more efficient for you to just loop through it. Though Rup's solution is a great use of LINQ here.
Here's a more complete version tailored for exactly what you want to do.
// count it
CountFiles(dest, di, #"*.xls");
public void CountFiles(TextWriter writer, DirectoryInfo directory, string searchPattern)
{
var counter = new FileGroupCounter
{
{ 5, Multiplier.K },
{ 10, Multiplier.K },
{ 20, Multiplier.K },
{ 100, Multiplier.K },
{ 1000, Multiplier.K },
{ 5, Multiplier.M },
{ 10, Multiplier.M },
{ 20, Multiplier.M },
{ 50, Multiplier.M },
{ 100, Multiplier.M },
};
foreach (var file in directory.EnumerateFiles(searchPattern, SearchOption.AllDirectories))
// or use GetFiles() if you're not targeting .NET 4.0
{
counter.CountFile(file);
}
foreach (var result in counter)
{
writer.WriteLine("Excel File " + result);
writer.WriteLine(result.Count);
writer.WriteLine();
}
}
// and the supporting classes
public enum Multiplier : long
{
K = 1 << 10,
M = 1 << 20,
G = 1 << 30,
T = 1 << 40,
}
public class FileGroupCounter : IEnumerable<FileGroupCounter.Result>
{
public ReadOnlyCollection<long> Limits { get { return roLimits; } }
public ReadOnlyCollection<int> Counts { get { return roCounts; } }
public ReadOnlyCollection<Multiplier> Multipliers { get { return roMultipliers; } }
public FileGroupCounter()
{
limits = new List<long>();
counts = new List<int>();
multipliers = new List<Multiplier>();
roLimits= limits.AsReadOnly();
roCounts= counts.AsReadOnly();
roMultipliers= multipliers.AsReadOnly();
}
private List<long> limits;
private List<int> counts;
private List<Multiplier> multipliers;
private ReadOnlyCollection<long> roLimits;
private ReadOnlyCollection<int> roCounts;
private ReadOnlyCollection<Multiplier> roMultipliers;
private long CalculateLength(int index)
{
return limits[index] * (long)multipliers[index];
}
public void Add(long limit, Multiplier multiplier)
{
int lastIndex = limits.Count - 1;
if (lastIndex >= 0 && limit * (long)multiplier <= CalculateLength(lastIndex))
throw new ArgumentOutOfRangeException("limit, multiplier", "must be added in increasing order");
limits.Add(limit);
counts.Add(0);
multipliers.Add(multiplier);
}
public bool CountFile(FileInfo file)
{
if (file == null)
throw new ArgumentNullException("file");
for (int i = 0; i < limits.Count; i++)
{
if (file.Length <= CalculateLength(i))
{
counts[i]++;
return true;
}
}
return false;
}
public IEnumerator<Result> GetEnumerator()
{
for (int i = 0; i < limits.Count; i++)
{
if (counts[i] > 0)
yield return new Result(this, i);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
public class Result
{
public long Limit { get { return counter.limits[index]; } }
public int Count { get { return counter.counts[index]; } }
public Multiplier Multiplier { get { return counter.multipliers[index]; } }
internal Result(FileGroupCounter counter, int index)
{
this.counter = counter;
this.index = index;
}
private FileGroupCounter counter;
private int index;
public override string ToString()
{
if (index > 0)
return String.Format("> {0} {1}B and <= {2} {3}B",
counter.limits[index - 1], counter.multipliers[index - 1],
counter.limits[index], counter.multipliers[index]);
else
return String.Format("<= {0} {1}B",
counter.limits[index], counter.multipliers[index]);
}
}
}
I think only real optimisation here would be to ensure you only call di.GetFiles("*.xls", SearchOption.TopDirectoryOnly) once - since that will actually hit the filesystem rather than being lazily executed like most LINQ. Sure, the filesystem will cache the results of this but can't be slower to stay in memory and reuse the list.
Once you're in memory Jeff might be right - just count yourself - thought that doesn't seem very elegant :-) and it probably doesn't make a lot of difference here unless you're dealing with huge numbers. You just want to try and keep the number of allocations / reallocations down. With as much LINQ as I can cram in
var files = di.GetFiles("*.xls", SearchOption.TopDirectoryOnly);
// map to a list of numbers, 0 = up to 5K, 1 = 5-10, etc.
var sizes = files.Select(f => (f.Length / 5120));
var countsBySize = sizes.GroupBy(s => s)
.Select(g => new { Size = g.Key, Count = g.Count() })
.OrderBy(s => s.Size);
var results = countBySize.ToList();
which returns a list of 5K buckets and count of files in each bucket. If you're just going to foreach this then don't do the final ToList. If you wanted the individual files in each bucket you should group by the (f.Length / 5120) without selecting it first.

how to pass an id number string to this class

I'm very much a vb person, but have had to use this id number class in c#. I got it from http://www.codingsanity.com/idnumber.htm :
namespace Utilities
{
[Serializable]
public class IdentityNumber
{
public enum PersonGender
{
Female = 0,
Male = 5
}
public enum PersonCitizenship
{
SouthAfrican = 0,
Foreign = 1
}
static Regex _expression;
Match _match;
const string _IDExpression = #"(?<Year>[0-9][0-9])(?<Month>([0][1-9])|([1][0-2]))(?<Day>([0-2][0-9])|([3][0-1]))(?<Gender>[0-9])(?<Series>[0-9]{3})(?<Citizenship>[0-9])(?<Uniform>[0-9])(?<Control>[0-9])";
static IdentityNumber()
{
_expression = new Regex(_IDExpression, RegexOptions.Compiled | RegexOptions.Singleline);
}
public IdentityNumber(string IDNumber)
{
_match = _expression.Match(IDNumber.Trim());
}
public DateTime DateOfBirth
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
int year = int.Parse(_match.Groups["Year"].Value);
// NOTE: Do not optimize by moving these to static, otherwise the calculation may be incorrect
// over year changes, especially century changes.
int currentCentury = int.Parse(DateTime.Now.Year.ToString().Substring(0, 2) + "00");
int lastCentury = currentCentury - 100;
int currentYear = int.Parse(DateTime.Now.Year.ToString().Substring(2, 2));
// If the year is after or at the current YY, then add last century to it, otherwise add
// this century.
// TODO: YY -> YYYY logic needs thinking about
if(year > currentYear)
{
year += lastCentury;
}
else
{
year += currentCentury;
}
return new DateTime(year, int.Parse(_match.Groups["Month"].Value), int.Parse(_match.Groups["Day"].Value));
}
}
public PersonGender Gender
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
int gender = int.Parse(_match.Groups["Gender"].Value);
if(gender < (int) PersonGender.Male)
{
return PersonGender.Female;
}
else
{
return PersonGender.Male;
}
}
}
public PersonCitizenship Citizenship
{
get
{
if(IsUsable == false)
{
throw new ArgumentException("ID Number is unusable!", "IDNumber");
}
return (PersonCitizenship) Enum.Parse(typeof(PersonCitizenship), _match.Groups["Citizenship"].Value);
}
}
/// <summary>
/// Indicates if the IDNumber is usable or not.
/// </summary>
public bool IsUsable
{
get
{
return _match.Success;
}
}
/// <summary>
/// Indicates if the IDNumber is valid or not.
/// </summary>
public bool IsValid
{
get
{
if(IsUsable == true)
{
// Calculate total A by adding the figures in the odd positions i.e. the first, third, fifth,
// seventh, ninth and eleventh digits.
int a = int.Parse(_match.Value.Substring(0, 1)) + int.Parse(_match.Value.Substring(2, 1)) + int.Parse(_match.Value.Substring(4, 1)) + int.Parse(_match.Value.Substring(6, 1)) + int.Parse(_match.Value.Substring(8, 1)) + int.Parse(_match.Value.Substring(10, 1));
// Calculate total B by taking the even figures of the number as a whole number, and then
// multiplying that number by 2, and then add the individual figures together.
int b = int.Parse(_match.Value.Substring(1, 1) + _match.Value.Substring(3, 1) + _match.Value.Substring(5, 1) + _match.Value.Substring(7, 1) + _match.Value.Substring(9, 1) + _match.Value.Substring(11, 1));
b *= 2;
string bString = b.ToString();
b = 0;
for(int index = 0; index < bString.Length; index++)
{
b += int.Parse(bString.Substring(index, 1));
}
// Calculate total C by adding total A to total B.
int c = a + b;
// The control-figure can now be determined by subtracting the ones in figure C from 10.
string cString = c.ToString() ;
cString = cString.Substring(cString.Length - 1, 1) ;
int control = 0;
// Where the total C is a multiple of 10, the control figure will be 0.
if(cString != "0")
{
control = 10 - int.Parse(cString.Substring(cString.Length - 1, 1));
}
if(_match.Groups["Control"].Value == control.ToString())
{
return true;
}
}
return false;
}
}
}
}
Can someone please tell the syntax for how I pass an id number to the class?
You'll have to use the constructor.
var someNumber = new IdentityNumber("123456");
Then, you can use the properties of that class to find out the specifics of that Id number.
Console.WriteLine (someNumber.DateOfBirth);
Console.WriteLine (someNumber.Gender);
Console.WriteLine (someNumber.Citizenship);
Console.WriteLine (someNumber.IsValid);
Console.WriteLine (someNumber.IsUsable);
IdentityNumber number = new IdentityNumber("123456");
All you need is to use provided Constructor like
IdentityNumber someNumber = new IdentityNumber("006834");

Categories

Resources