c#,arrays,loops , Iterating through array elements when arrays are stored in a list in c#

Iterating through array elements when arrays are stored in a list in c#


Tag: c#,arrays,loops

I have a small dilemma. I am writing a small application and am at the end stage of it, and cant decide the best way to go about this.

The program takes a string from the user in a textbox control.

From there it iterates over each character in the string: for each character it has, there is a matching array of substitute characters. Those arrays get added to a list<string[]>

From there though, I would like to iterate once more to generate another list which would create substitute words for the users input, gathering all possible combinations.

For example, DAN would become Dan, DaN, DAn, [email protected], and so on, using whatever characters were available.

The program supports only 0-9 and a-z (either case) at this point. I start inside the class declaring/defining a few arrays and lists:

    public List<String> passwordList = new List<String>();
    public List<string[]> arrayList = new List<string[]>();
    public int arrayListLength;

    public string[] zeroArray = {"0", "o", "O"}; //line for number 0
    public string[] oneArray = {"1", "!", "I", "i", "|"}; //line for number 1
    public string[] twoArray = {"2"}; //line for number 2
    public string[] threeArray = {"3"}; //line for number 3
    public string[] fourArray = {"4", "a", "A"}; //line for number 4
    public string[] fiveArray = {"5", "s", "S", "$"}; //line for number 5
    public string[] sixArray = {"6"}; //line for number 6
    public string[] sevenArray = {"7"}; //line for number 7
    public string[] eightArray = {"8"}; //line for number 8
    public string[] nineArray = {"9"}; //line for number 9

    public string[] aArray = {"a", "A", "4", "@"}; //line for letter a
    public string[] bArray = {"b", "B", "8"}; //line for letter b
    public string[] cArray = {"c", "C", "("};//line for letter c
    public string[] dArray = {"d", "D"}; //line for letter d
    public string[] eArray = {"e", "E"}; //line for letter e
    public string[] fArray = {"f", "F"}; //line for letter f
    public string[] gArray = {"g", "G"}; //line for letter g
    public string[] hArray = {"h", "H"}; //line for letter h
    public string[] iArray = {"i", "I", "!", "|"}; //line for letter i
    public string[] jArray = {"j", "J"}; //line for letter j
    public string[] kArray = {"k", "K"}; //line for letter k
    public string[] lArray = {"l", "L"}; //line for letter l
    public string[] mArray = {"m", "M"}; //line for letter m
    public string[] nArray ={"n", "N"}; //line for letter n
    public string[] oArray = {"o", "O", "0"}; //line for letter o
    public string[] pArray = {"p", "P"}; //line for letter p
    public string[] qArray = {"q", "Q"}; //line for letter q
    public string[] rArray = {"r", "R"}; //line for letter r
    public string[] sArray = {"s", "S", "5", "$"}; //line for letter s
    public string[] tArray = {"t", "T", "+"}; //line for letter t
    public string[] uArray = {"u", "U"}; //line for letter u
    public string[] vArray = {"v", "V"}; //line for letter v
    public string[] wArray = {"w", "W"}; //line for letter w
    public string[] xArray = {"x", "X"}; //line for letter x
    public string[] yArray = {"y", "Y"}; //line for letter y
    public string[] zArray = {"z", "Z"}; //line for letter z

Later, when iterating, the loop looks something like this:

 String generateFrom = txtGenerateFrom.Text;

        foreach (char c in generateFrom)
            if (c.ToString() == "0")
            else if (c.ToString() == "1")
            else if (c.ToString() == "2")
            else if (c.ToString() == "3")
            else if (c.ToString() == "4")
            else if (c.ToString() == "5")
            else if (c.ToString() == "6")
            else if (c.ToString() == "7")
            else if (c.ToString() == "8")
            else if (c.ToString() == "9")
            else if (c.ToString() == "a" || c.ToString() == "A")
            else if (c.ToString() == "b" || c.ToString() == "B")
            else if (c.ToString() == "c" || c.ToString() == "C")

This gets me a list (public List<string[]> arrayList = new List<string[]>();//declared at beginning ) which contains the relevant arrays, and the arrays are in order by where they belong relevant to the user input.

What then is the best way to loop over this list to make my strings and add them to a list of words which can substitute?


Try this class:

public static class PasswordGenerator
    private static readonly IReadOnlyDictionary<char, char[]> Substitutions = new Dictionary<char, char[]> {
        {'0', new[] {'0', 'o', 'O'}},
        {'1', new[] {'1', '!', 'I', 'i', '|'}},
        {'2', new[] {'2'}},
        {'3', new[] {'3'}},
        {'4', new[] {'4', 'a', 'A'}},
        {'5', new[] {'5', 's', 'S', '$'}},
        {'6', new[] {'6'}},
        {'7', new[] {'7'}},
        {'8', new[] {'8'}},
        {'9', new[] {'9'}},
        {'a', new[] {'a', 'A', '4', '@'}},
        {'b', new[] {'b', 'B', '8'}},
        {'c', new[] {'c', 'C', '('}},
        {'d', new[] {'d', 'D'}},
        {'e', new[] {'e', 'E'}},
        {'f', new[] {'f', 'F'}},
        {'g', new[] {'g', 'G'}},
        {'h', new[] {'h', 'H'}},
        {'i', new[] {'i', 'I', '!', '|'}},
        {'j', new[] {'j', 'J'}},
        {'k', new[] {'k', 'K'}},
        {'l', new[] {'l', 'L'}},
        {'m', new[] {'m', 'M'}},
        {'n', new[] {'n', 'N'}},
        {'o', new[] {'o', 'O', '0'}},
        {'p', new[] {'p', 'P'}},
        {'q', new[] {'q', 'Q'}},
        {'r', new[] {'r', 'R'}},
        {'s', new[] {'s', 'S', '5', '$'}},
        {'t', new[] {'t', 'T', '+'}},
        {'u', new[] {'u', 'U'}},
        {'v', new[] {'v', 'V'}},
        {'w', new[] {'w', 'W'}},
        {'x', new[] {'x', 'X'}},
        {'y', new[] {'y', 'Y'}},
        {'z', new[] {'z', 'Z'}}

    public static IEnumerable<string> GenerateFor(string value)
        if (value == null)
            throw new ArgumentNullException("value");
        return GenerateFor(value, value.ToCharArray());

    private static IEnumerable<string> GenerateFor(string src, char[] value, int index = 0)
        if (index < value.Length)
            char[] chars;
            while (!Substitutions.TryGetValue(char.ToLowerInvariant(src[index]), out chars))
                if (++index == src.Length)
                    yield return new string(value);
                    yield break;

            foreach (var c in chars)
                value[index] = c;
                foreach (var nextValue in GenerateFor(src, value, index + 1))
                    yield return nextValue;
            yield return new string(value);

You can use it like this:

foreach (var password in PasswordGenerator.GenerateFor("DAN"))

And this code output:

[email protected]
[email protected]
[email protected]
[email protected]


Translating a character array into a integer string in C++

I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?

I created a small wrapper around CancellationToken and CancellationTokenSource. The problem I have is that the CancelAsync method of CancellationHelper doesn't work as expected. I'm experiencing the problem with the ItShouldThrowAExceptionButStallsInstead method. To cancel the running task, it calls await coordinator.CancelAsync();, but the task is not cancelled actually and doesn't...

how can I add a column to IQueryable object and modify its values

var packs = from r in new XPQuery<Roll>(session) select new { Number = r.number Selection = new bool() }; gcPack.DataSource = packs; I want to add another column to my grid control with: Selection = new bool(). It will be added to the grid but I can't change its...

Aligning StackPanel to top-center in Canvas

I'm trying to create an application which is supposed to measure quick reaction performance of it's user. The application starts up in full-screen mode and resizes it's elements accordingly to the screen resolution. The project was strongly inspired by training_aim_csgo2 map. It's mostly done, but here is the problem: I...

deployment of a site asp.net and iis

I know this is for some of you a stupid question but for me is a real problem. I have never deployed a site before What i have done so far: 1) publish the site from visual studio to a folder. 2) added to iis for testing everything works great...

Collect strings after a foreach loop

Is it possible to collect the strings after a foreach loop? For example: StringCollection col = new StringCollection(); XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); foreach (XmlNode skillNameNode in skillNameNodeList) { skillsName=skillNameNode.Attributes["value"].Value; } col.Add(skillsName); //Return System.Collections.Specialized.StringCollection I want to collect each skillsName and put them in a collection or a list so that I can...

Load XML to list using LINQ [duplicate]

This question already has an answer here: XDocument to List of object 1 answer I have following XML: <?xml version="1.0" encoding="utf-8"?> <start> <Current CurrentID="5"> <GeoLocations> <GeoLocation id="1" x="78492.61" y="-80973.03" z="-4403.297"/> <GeoLocation id="2" x="78323.57" y="-81994.98" z="-4385.707"/> <GeoLocation id="3" x="78250.57" y="-81994.98" z="-4385.707"/> </GeoLocations> <Vendors> <Vendor id = "1" x="123456" y="456789" z="0234324"/>...

How to Customize Visual Studio Setup

I have created a video chat application in c#. Now I wan to make a setup of it. I have created a setup using Visual studio's setup project but my client told me to customize the setup progress bar styles and other properties. i dont know how to do it....

How to return result while applying Command query separation (CQS)

I am separating my query and command on service side like this: public class ProductCommandService{ void AddProduct(Product product); } public interface ProductQueryService{ Product GetProduct(Guid id); Product[] GetAllProducts(); } Command Query Separation accepts that a method should change state or return a result. There is no problem. public class ProductController: ApiController{...

Foreign key in C#

I have two tables, A and B, in a dataset in SQL Server; I have created a connection to the dataset in a c# project in visual studio. How can I create a foreign key ( A is the parent) between my two tables ? I want to create the...

C# PCL HMACSHAX with BouncyCastle-PCL

I want to implement this logic in portable C# class: static JsonWebToken() { HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> { { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } }, { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new...

How to declare var datatype in public scope in c#?

I write simple query with linq to sql : var query = (from p in behzad.GAPERTitles select new { p.id, p.gaptitle }).ToArray(); up code into the c# windows application ,windows form load event,and i want use up result into the button click event in this scope: private void button1_Click(object sender,...

Merge and sum values and put them in an array

I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

Regex to remove `.` from a sub-string enclosed in square brackets

I have this regex in C#: \[.+?\] This regex extracts the sub-strings enclosed between square brackets. But before doing that I want to remove . inside these sub-strings. For example, the string hello,[how are yo.u?]There are [300.2] billion stars in [Milkyw.?ay]. should become hello,[how are you?]There are [3002] billion stars...

Convert contents of an XmlNodeList to a new XmlDocument without looping

I have Xml that I filter using XPath (a query similar to this): XmlNodeList allItems = xDoc.SelectNodes("//Person[not(PersonID = following::Person/PersonID)]"); This filters all duplicates from my original Persons Xml. I want to create a new XmlDocument instance from the XmlNodeList generated above. At the minute, the only way I can see...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column...

check if file is image

I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

Substring of a file

I have a file that is structure like this : var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this: var array = [ [a,b,1], [a,b,2], [a,b,3], [a,b,4], [a,b,5] ]; How...

Update list of items in c#

I would like to know if you can suggest me an efficient way to update a list of items in c#. Here is a generic example: If CurrentList is [ {Id: 154, Name: "George", Salary: 10 000} {Id: 233, Name: "Alice", Salary: 10 000}] And NewList is [ {Id: 154,...

Ruby: How to copy the multidimensional array in new array?

seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Access manager information from Active Directory

Attach is the picture of active directory, which i got from my IT department. Now i want to get the manager information in C#. NOTE: I am able to get all information of user but there isn't any key of manager, but IT department just gave me above attached...

pointer to pointer dynamic array in C++

I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

C# Code design / Seperate classes for each TabControl

My main problem is that my tool grows and grows and I start loosing the focus on the different parts of my code. The main-Form got a docked tabControl at fullsize. I got 5 different tabs with for really different functions. So I can say my tool is splitted into...

Create array from another with specific indices

I have two arrays, one of data and one of indices: var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; I would like to create a third array, using cells of data in order indicated...

Get elements containing text from array

I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

array and function php

I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. If you could help me, I'd be much obliged. I'm having trouble understanding why the following code doesn't work. <?php function sum($x, $y) { $z = $x + $y;...

while Inherit style in WPF it affect parent style

In WPF i have a style for the control like below, <Style TargetType="local:CustomControl"> <Setter Property="Background" Value="Transparent" /> <Setter Property="BorderBrush" Value="Gray" /> <Setter Property="BorderThickness" Value="0,0,0,1" /> <Setter Property="Padding" Value="3,0,3,0" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="VerticalContentAlignment" Value="Center" /> </Style> Now i need to override customcontrol border for some other place like...

How to pivot array into another array in Ruby

I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

Visual Studio Assembly force-installs Target Framework

I have this Assembly targeted at .NET 3.5. The code will work on later versions as well, but I like this to work on Windows XP. I mean, .NET is backwards compatible, right? I can run apps for .NET 3.5 on Windows 8.1. However, when I run my own assembly,...

Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?

To bind a value to a TextBlock we use the following syntax to display an <ItemName> property of a bounded object. <TextBlock Text="{Binding Path=ItemName}" /> But is there a syntax to use the above tag to concatenate the constant string 'Item' with the databounded property, in order display something like:...

How do I provide a collection of elements to a custom attached property?

I found a few examples online, and a few questions and answers here, but I just can't get it to work. I need a custom attached property that can take one or more target elements. For example... <ListView> <dd:MyDragDrop.DropBorders> <Binding ElementName="brdOne"/> <Binding ElementName="brdTwo"/> <Binding ElementName="brdThree"/> </dd:MyDragDrop.DropBorders> </ListView> I've also had...

Memory consumption when chaining string methods

I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string? If it is true, what is the best practice to do too many manipulations on a string using chaining methods?...

C# XML: System.InvalidOperationException

I have been learning C#'s XML with a project however I keep getting the InvalidOperationException. I have put the code below XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor Name"); writer.WriteString(tutorName); writer.WriteEndElement();...

Get object by attribute value [duplicate]

This question already has an answer here: How enumerate all classes with custom class attribute? 4 answers I have a set of classes which implement a common interface and are annotated with a business domain attribute. By design, each class is annotated with different parametrization [Foo(Bar=1)] public class EntityA...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

I need to save a file which is in an External application using SendKeys.Send() method. The keys needed to be sent are Ctrl+S. I wrote the below code, but its not working: SendKeys.SendWait("^%s?"); // to get the Save As dialog Thread.Sleep(5000); SetForegroundWindow(FindWindow(null, "Save As")); Thread.Sleep(5000); SendKeys.SendWait("xyz"); // Sending FileName ...

Multiple Threads searching on same folder at same time

Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

How can I determine if an object of anonymous type is empty?

I am sure the answer to this is quite simple but I am trying to write an if statement (C# 5.0) to determine whether or not an anonymous type is empty or not. Here is a simplified version of my code: public void DoSomething(object attributes) { // This is the...

Javascript function to validate contents of an array

Here's what is asked: validItems(items) – this function receives a string array of items which are to be for a customer. The function returns an empty string indicating all item codes in the array are valid; otherwise the function returns the first invalid item code in the array. All item...

Catch concurrency exception in EF6 to change message to be more user friendly

I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Difference between application and module pipelines in Nancy?

I have seen in the documentation of Nancy, sometimes these two are referred distinctively. And also is there a difference in the Before/After hooks of these two pipelines?...

Marshal struct in struct from c# to c++

I have the following structures in C# and C++. C++: struct TestA { char* iu; }; struct TestB { int cycle1; int cycle2; }; struct MainStruct { TestA test; TestB test2; }; C#: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack = 1)] internal struct TestA { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; public...

System.net.http.formatting causing issues with Newtonsoft.json

My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version I assumed this would not be a problem, as I could just use a...

Infinite loop with fread

I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

Blank screen on GridView

I'm trying to create a GridView with an array of strings. These are XML, and MainActivity and Adapter, but what I get is a blank screen. I'm change the background, but the result is the same, but clicking on a point on the screen appears to me the toast stating...

Regex that allow void fractional part of number

@"[+-]?\d+(\.\d+)?" -this is a regex I have wrote for numbers it allows [+-] minus before the number digits before and digits after the point the question is how to change this to allow "not finished" values so that input of "5." - is fine too ?...

Index was out of range. Must be non-negative or less than size of collection [duplicate]

This question already has an answer here: What is an “index out of range” exception, and how do I fix it? [duplicate] 1 answer Trying to run a delete application in C#. If there is more than 10 files in a directory, delete the oldest file, and iterate again....

Convert Date Time to IST

I want to convert the date time to "Indian Standard Time", so i used the following code :- public static TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("Indian Standard Time"); writer.WriteLine("{0} {1}", indianTime.ToLongTimeString(), indianTime.ToLongDateString()); The above code gives me error :- System.TimeZoneNotFoundException: The time zone ID 'Indian Standard Time' was not found on the...

Validate a field only if it is populated

I am having a problem with validating phone numbers. In our system we have two phone numbers which you can store. The problem I am having is that these are optional fields. So I want it to validate the phone number IF and only IF the user has tried to...

Javascript sort array of objects in reverse chronological order

I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...