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++;
}
Related
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to get count the elements in an array but without linq
Example:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
And
desired result is : cat=2, dog=1, horse=1
Here's one way I could think of using a Dictionary<string, int>:
public static Dictionary<string, int> GetObjectCount(List<string> items)
{
// Dictionary object to return
Dictionary<string, int> keysAndCount = new Dictionary<string, int>();
// Iterate your string values
foreach(string s in items)
{
// Check if dictionary contains the key, if so, add to count
if (keysAndCount.ContainsKey(s))
{
keysAndCount[s]++;
}
else
{
// Add key to dictionary with initial count of 1
keysAndCount.Add(s, 1);
}
}
return keysAndCount;
}
Then get the result back and print to console:
Dictionary<string, int> dic = GetObjectCount(list);
//Print to Console
foreach(string s in dic.Keys)
{
Console.WriteLine(s + " has a count of: " + dic[s]);
}
I am not sure why are you looking for LINQ less solution for this as this could be done very easily and efficiently by it. I strongly suggest you to use it and do it like below :
var _group = list.GroupBy(i => i);
string result = "";
foreach (var grp in _group)
result += grp.Key + ": " + grp.Count() + Environment.NewLine;
MessageBox.Show(result);
Otherwise you can do it like below if you really unable to use LINQ :
Dictionary<string, int> listCount = new Dictionary<string, int>();
foreach (string item in list)
if (!listCount.ContainsKey(item))
listCount.Add(item, 1);
else
listCount[item]++;
string result2 = "";
foreach (KeyValuePair<string, int> item in listCount)
result2 += item.Key + ": " + item.Value + Environment.NewLine;
MessageBox.Show(result2);
The simple solution to your issue is a foreach loop.
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
Console.WriteLine($"There are {GetCount(myStrings, "cat");} cats.");
static int GetCount(string[] strings, string searchTerm) {
int result = 0;
foreach (string s in strings)
if (s == searchTerm)
result++;
return result;
}
Linq does this under the hood. However, unless this is either for optimization of large lists or for learning experience, Linq should be your preferred choice if you know how to use it. It exists to make your life easier.
Another implementation of this would be to simplify the number of calls you need and just write the output in the method:
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
CountTerms(myStrings, "cat", "dog");
Console.ReadKey();
static void CountTerms(string[] strings, params string[] terms) {
foreach (string term in terms) {
int result = 0;
foreach (string s in strings)
if (s == term)
result++;
Console.WriteLine($"There are {result} instances of {term}");
}
}
With that said, I heavily recommend Ryan Wilson's answer. His version simplifies the task at hand. The only downside to his implementation is if you are implementing this in a singular manner the way List<string>.Count(c => c == "cat") would.
You could try something like:
public int countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countSoFar;
}
this will give you the count for any sting you give it. As always there is a better way but this is a good start.
Or if you want:
public string countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
string result = countFor;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countFor + " = " countSoFar;
}
Or an even better option:
private static void CountOccurances(List<string> inputList, string countFor)
{
int result = 0;
foreach (string s in inputList)
{
if (s == countFor)
{
result++;
}
}
Console.WriteLine($"There are {result} occurrances of {countFor}.");
}
Linq is supposed to make developer's life easy. Anyway you could make something like this:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
var result = GetCount(list);
Console.WriteLine(result);
Console.ReadLine();
static string GetCount(List<string> obj)
{
string result = string.Empty;
int cat = 0;
int dog = 0;
int horse = 0;
foreach (var item in obj)
{
switch (item)
{
case "dog":
dog++;
break;
case "cat":
cat++;
break;
case "horse":
horse++;
break;
}
}
result = "cat = " + cat.ToString() + " dog = " + dog.ToString() + " horse = " + horse.ToString();
return result;
}
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 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?
Is there any other shorter/more efficient way to check and see if it is the last item in my ListBox? The main goal here is basically to add the selected items to a label, and add a comma after every one but the last one. Any suggestions?
int sc = 0;
List<string> interestitems = new List<string>();
foreach (ListItem siitem in ListBox1.Items)
{
if (siitem.Selected == true)
{
interestitems.Add(siitem.Value.ToString());
}
}
foreach (string inteitem in interestitems)
{
Label1.Text += inteitem;
sc++;
if (sc < interestitems.Count)
{
Label1.Text += ",";
}
}
Instead of your second loop just use:
Label1.Text = string.Join("," , interestitems);
P.S.
if you're using .net 3.5, you need to pass an array of strings to string.Join(), then :
Label1.Text = string.Join("," , interestitems.ToArray());
EDIT:
If you want to completely avoid looping just do:
var selItems = ListBox1.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => item.ToString());
Label1.Text = string.Join("," , selItems);
How about LINQ:
Label1.Text = string.Join(
",",
ListBox1.Items
.OfType<ListItem>()
.Where(item => item.Selected)
.Select(x => x.Value.ToString())
.ToArray()
);
You can replace all of your code with some LINQ:
Label1.Text = String.Join(", ",
ListBox1.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value.ToString())
);
In .Net 3.5, you'll need to add .ToArray().
I believe you can do this:
interestitems.IndexOf(inteitem);
Altought it worked me with other item types, may give you an idea. I haven't checked if it works with strings.
The you just have to eliminate the last one, with the index check if it's the last ones with interestitems.Count
Why not just build up the string as you iterate during the first loop
var builder = new StringBuilder();
var first = true;
foreach (var item in ListBox1.Items) {
if (item.Selected) {
if (!first) {
builder.Append(", ");
}
first = false;
builder.Append(item.Value.ToString());
}
}
Label1.Text = builder.ToString();