Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C#] Switch Array Values - LINQ
#1
Here's another cool snippet i've been working with lately and which someone might find useful or would like to experiment with Smile

Basically you can take one array value and define another for it by a simple "swap" with the help of LINQ. Great use of classes in this example too.

Code:
string[] strN = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int[] intN = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

List<SwitchClass> sc = new List<SwitchClass>();
for (int i = 0; i < strN.Length; i++)
{
    sc.Add(new SwitchClass {WordNum = strN[i], IntNum = intN[i]});
}

int gval = 7;
SwitchClass num = sc.FirstOrDefault(n => n.IntNum == gval);
MessageBox.Show(num != null ? num.WordNum : "Undefined/Nonexistant");

And here's the class that we're going to utilize within this example:
Code:
private class SwitchClass
{
    public string WordNum;
    public int IntNum;
}

The way this works revolves around the First/FirstOrDefault method. I've defined 2 arrays in position so that when they get added to the list of SwitchClass (user defined type), they are already created in sync so that each value inside the switchclass list contains proportional "data". Meaning an item in this list will contain for each of the 2 properties, their comparable int and word value within the same item.

Ex: sc item 1 at index of 0 in the list of SwitchClass will contain (based on this for loop) a property of WordNum and IntNum, IntNum containing an integer value and WordNum containing the string value in word of that integer value. So in this case the first item would contain IntNum = 0, and WordNum = "zero" properties.

Now is where FirstOrDefault comes in, we use this to find our Integer value (int/Int32) within the list of SwitchClass (sc) by checking each item property of .IntNum and seeing if it matches our gval int variable. If it does then that is what SwitchClass our num variable now holds, otherwise it will go undefined, and we'll check for that later if you read on.

Now that we hopefully defined the num variable (if not it's okay), we can go ahead and display the WordNum property of that item based on the IntNum property we've searched for by query. If num is not null, that means we've found a match of the IntNum property we've searched for and we can display the WordNum property of that SwitchClass user defined type from the list of SwitchClass we've created. Otherwise if it is null, that means we could not find a value, and therefore based on our if statement logic, we can display "Undefined/Nonexistant" in the textbox when running through this code.

Enjoy, hope you've learned Smile Any questions just ask.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Add Multiple textbox values to email? Extasey 3 1,979 03-01-2010, 02:35 AM
Last Post: Extasey

Forum Jump:


Users browsing this thread: 1 Guest(s)