Three combination of dimension array in C#? - c#

How do I create three combinations of dimension array in C#?, I am getting error message
index was outside of the bounds of the array.
foreach (XmlNode RegexExpression in XmlDataAccess.GetElementList(RefFile, "//regex"))
{
xRefList.Add(RegexExpression.InnerText);
}
foreach (XmlNode RegexExpression in XmlDataAccess.GetElementList(RefFile, "//word"))
{
WordList.Add(RegexExpression.InnerText);
}
foreach (XmlNode RegexExpression in XmlDataAccess.GetElementList(RefFile, "//title"))
{
TitleList.Add(RegexExpression.InnerText);
}
ArrayList xRefResult = MainDocumentPart_Framework.getReferenceContent(FileName, xRefList);
ArrayList TitleResult = MainDocumentPart_Framework.getReferenceContent(FileName, TitleList);
ArrayList WordResult = MainDocumentPart_Framework.getReferenceContent(FileName, WordList);
var FinalResult = from first in TitleResult.ToArray()
from second in WordList.ToArray()
from third in xRefResult.ToArray()
select new[] { first, second, third };
foreach (var Item in FinalResult)
{
System.Windows.MessageBox.Show(Item.ToString());
//I like to view show, all the combination of arrays
//first1, second1, third1
//first1, second1, third2
//first1, second1, third3 ...........
}

I'm not really sure what kind of output you're after, and I don't think you need to use LINQ for this.
string outputStr = "";
for(int x = 0;x<xRefList.Count;x++)
{
for(int y = 0;y<WordList.Count;y++)
{
for(int z = 0;z<TitleList.Count;z++)
{
outputStr += xRefList[x] + " " + WordList[y] + " " + TitleList[z] + "\n";
}
}
}
MessageBox.Show(outputStr);
Would something like this work?

Related

Merging two items into one inside a List<string> in C#

I have a List<string> with the name data with this items:
{ A101, Plans, A102, Elev/Sec, A103, Unnamed }
foreach (string item in data)
{
data1.Add(item + item);
}
I wanted the output to be like this:
A101 Plans
A102 Eleve/Sec
A103 Unnamed
But the output is:
A101 A101
Plans Plans
A102 A102
Eleve/Sec Eleve/Sec
A103 A103
Unnamed Unnamed
How can I fix this problem?
It's not easy to do with a foreach; you'd have to remember the previous element and put the combination into a list when the memory is not blank, then blank the memory
It's easier with a straight for that goes in jumps of two
for(int i=0; i < list.Length; i+=2){
Console.WriteLine(list[i] + " " + list[i+1]);
}
With a foreach it's like:
string x = null;
foreach(var item in list){
if(x == null){
x = item;
} else {
Console.WriteLine(x + " " + item);
x = null;
}
}
x flipflops between being null and something. When it is null, the item is remembered, when it is something the output is the "previous item i.e. x plus the current item"

Formatting List of String

I have an array of strings. I need to sort the list and save each letter's item in a single line. After this, I need to find the longest line of string.
I have done the first part in an inefficient way but I am trying to make it concise.
List<string> fruits = new List<string>
{
"Pomme",
"Apple",
"Apricots",
"Avocado",
"Banana",
"Blackberries",
"Blackcurrant",
"Blueberries",
"Cherries",
"Clementine",
"Cranberries",
"Custard-Apple",
"Durian",
"Elderberries",
"Feijoa",
"Figs",
"Gooseberries",
"Grapefruit",
"Grapes",
"Guava",
"Breadfruit",
"Cantaloupe",
"Carambola",
"Cherimoya",
};
fruits.Sort();
List<string> sortedString = new List<string> { };
foreach (var str in fruits)
{
sortedString.Add(str);
}
//string A, B, C, D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S;
var A = "";
var B = "";
var C = "";
var D = "";
var E = "";
var F = "";
var G = "";
foreach (var item in sortedString)
{
if (item.StartsWith('A'))
{
A += item;
}
else if (item.StartsWith('B'))
{
B += item;
}
else if (item.StartsWith('C'))
{
C += item;
}
else if (item.StartsWith('D'))
{
D += item;
}
else if (item.StartsWith('E'))
{
E += item;
}
else if (item.StartsWith('F'))
{
F += item;
}
}
The result will be like -
AppleApricotsAvocado
BananaBlackberriesBlackcurrantBlueberriesBreadfruit
CantaloupeCarambolaCherimoyaCherriesClementineCranberriesCustard-Apple
Durian
Elderberries
FeijoaFigs
GooseberriesGrapefruitGrapesGuava
After this, I need to find the longest line and put space between each item. Without effective looping, the code will be messy. Can you assist me to show the right way to solve the problem?
The Sort() method already sorts your list and you don't need to assign it to a new one.
My proposal to resolve your problem is
fruits.Sort();
var result = fruits.GroupBy(f => f[0]);
int[] lineslength = new int[result.Count()];
int index = 0;
foreach (var group in result)
{
foreach (var item in group)
{
lineslength[index] += item.Length;
Console.Write(item + " ");
}
Console.WriteLine();
index++;
}
int longestIndex = Array.FindIndex(lineslength, val => val.Equals(lineslength.Max()));
Console.WriteLine(longestIndex);
I used the GroupBy method to group strings by their first letter. Then when I was displaying strings I also counted their length. Using the static FindIndex method of the Array class, I found the index containing the maximum value of the array what corresponds to the line with the maximum length. So index zero is the first line, one is the second line etc.

First or Last element in a List<> in a foreach loop

I have a List<string> and I want to identify either the first or last element in the list so I can identify a different function to do with that item.
Eg.
foreach (string s in List)
{
if (List.CurrentItem == (List.Count - 1))
{
string newString += s;
}
else
{
newString += s + ", ";
}
}
How would I go about defining List.CurrentItem? Would a for loop be better in this situation?
Rather make use of String.Join
Concatenates the elements of a specified array or the members of a
collection, using the specified separator between each element or
member.
It is a lot simpler.
Something like
string s = string.Join(", ", new List<string>
{
"Foo",
"Bar"
});
You can use a linq based solution
Example :
var list = new List<String>();
list.Add("A");
list.Add("B");
list.Add("C");
String first = list.First();
String last = list.Last();
List<String> middle_elements = list.Skip(1).Take(list.Count - 2).ToList();
you can use the counter like this
int counter = 0 ;
foreach (string s in List)
{
if (counter == 0) // this is the first element
{
string newString += s;
}
else if(counter == List.Count() - 1) // last item
{
newString += s + ", ";
}else{
// in between
}
counter++;
}
Try something like this:
string newString = "";
foreach (string s in List)
{
if( newString != "" )
newString += ", " + s;
else
newString += s;
}

How to covert IpAddress items to string c#

I have a ListBox that contains a System.net.IPAddress and string items. I want to convert them all to strings. I have tried this as shown below but it says it can not cast from IPAddress to string.
var List4 = f.listBox4.Items.Cast<String>().ToList();
foreach (string i in List4)
{
cursheet.get_Range(colname + x).Value = i;
x++;
}
var List4 = f.listBox4.Items.Cast<object>().Select(x => x.ToString())
How about this? No need for linq, casting, etc..
foreach (var item in f.listBox4.Items)
{
cursheet.get_Range(colname + x).Value = item.Text;
x++;
}
Or, if you want the value:
foreach (var item in f.listBox4.Items)
{
cursheet.get_Range(colname + x).Value = item.Value;
x++;
}

How to merge values of two lists together

For example I have:
public static List<int> actorList = new List<int>();
public static List<string> ipList = new List<string>();
They both have various items in.
So I tried joining the values (string and int) together using a foreach loop:
foreach (string ip in ipList)
{
foreach (int actor in actorList)
{
string temp = ip + " " + actor;
finalList.Add(temp);
}
}
foreach (string final in finalList)
{
Console.WriteLine(finalList);
}
Although looking back at this, this was pretty stupid and obviously will not work, as the first forloop is nested.
My expected values for finalList list:
actorListItem1 ipListItem1
actorListItem2 ipListItem2
actorListItem3 ipListItem3
and so on..
So the values from the two lists are concatenated with each other - corresponding of their position in the lists order.
Use ZIP function of LINQ
List<string> finalList = actorList.Zip(ipList, (x,y) => x + " " + y).ToList();
finalList.ForEach(x=> Console.WriteLine(x)); // For Displaying
OR combine them in one line
actorList.Zip(ipList,(x,y)=>x+" "+y).ToList().ForEach(x=>Console.WriteLine(x));
What about some functional goodness?
listA.Zip(listB, (a, b) => a + " " + b)
Assuming you can use .NET 4, you want to look at the Zip extension method and the provided example:
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
// The following example concatenates corresponding elements of the
// two input sequences.
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
foreach (var item in numbersAndWords)
Console.WriteLine(item);
Console.WriteLine();
In this example, because there is no corresponding entry for "4" in words, it is omitted from the output. You would need to do some checking to make sure the collections are the same length before you start.
Loop over the indexes:
for (int i = 0; i < ipList.Count; ++i)
{
string temp = ipList[i] + " " + actorList[i];
finalList.Add(temp);
}
You may also want to add code before this to verify that the lists are the same length:
if (ipList.Count != actorList.Count)
{
// throw some suitable exception
}
for(int i=0; i<actorList.Count; i++)
{
finalList.Add(actorList[i] + " " + ipList[i]);
}

Categories