skip ahead in a foreach loop c# - c#

if I have a foreach loop that takes a whole bunch of addresses and loops through them, is there a way I could skip the first 500 entries,
something like:
foreach(var row in addresses)
{
string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
System.Threading.Thread.Skip(500)
}
I know skip doesn't exist but is there anything I can use that would do the same thing?

You can use a method with a meaningful name:
foreach(var row in addresses.Skip(500))
{
// ...
}
You need to add using System.Linq; since it's a LINQ extension method.
If the type of addresses doesn't implement the generic IEnumerable<T> interface you could use Cast<T>. For example (presuming the type is Address):
foreach(var row in addresses.Cast<Address>().Skip(500))
{
// ...
}

You can use the Skip extension method:
foreach(var row in addresses.Skip(500))
{
string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
}
Or, if addresses is just an array or list:
for (int i = 500 ; i < addresses.Count ; i++) // assuming addresses is a List<T>
{
var row = addresses[i];
string strAddr = row.ADDRESS + "," + row.CITY + "," + row.ST;
}

Use the Enumerator interface directly: http://msdn.microsoft.com/en-us/library/system.collections.ienumerator(v=vs.110).aspx
var enumerator = addresses.GetEnumerator();
for (var i = 0; i < 300 && enumerator.MoveNext(); i++);

A feasible and fast solution would be to use LINQ Skip method to iterate over a subset of the collection starting from the 500th element of the collection.
foreach (var row in addresses.Skip(500))
{
// do your stuff...
}

Related

ForEach In List isn't targetting all

so I currently have a program that adds an item to a list in a format such as
username,Index it then adds one to the index in this code below however. It is only adding one to the item that has been added most recently.
Console.WriteLine("There are currently: " + AntiSpam.Count);
int Index = 0;
foreach (string s in AntiSpam)
{
Console.WriteLine("Found User: " + s.Split(',')[0]);
AntiSpam[Index] = s.Split(',')[0] + "," + (int.Parse(s.Split(',')[1]) + 1).ToString();
Index++;
}
Basically this returns the data There are currently: 10
Found User: someone. It then goes again for another loop of this code and shows the same result again.
EDIT
I have managed to make my code work by using this code
for (var i = 0; i < AntiSpam.Count; i++)
{
AntiSpam[i] = AntiSpam[i].Split(',')[0] + "," + (int.Parse(AntiSpam[i].Split(',')[1]) + 1).ToString();
Console.WriteLine("Text is {0}", AntiSpam[i]);
}
However if possible I would like to know why this works and the first doesn't
If you're going to be indexing a list, just do for rather than foreach. This avoids the need (and possible confusion) of using a separate variable to keep track of the AntiSpam.IndexOf(s) which is basically what you were trying to do with Index:
Console.WriteLine("There are currently: " + AntiSpam.Count);
int index;
string s;
for(int i=0; i < AntiSpam.Count, i++)
{
string[] parts = AntiSpam[i].Split(',');
username = parts[0];
Console.WriteLine("Found User: " + username);
if (parts.Length > 1)
{
index = int.Parse(parts[1])
AntiSpam[i] = username + "," + (index + 1).ToString();
}
}

String substitution in C#

I have a list of names and I loop through them to create a comma separated list in a string variable (Bob, George, Will, Terry).
I need the list to eventually look like (Bob, George, Will and Terry).
How do I find the LAST instance of the comma and replace it with the word "and"? Once I find the LAST instance, I think it's a simple matter of doing something like
string new=ori.Substring(0,start) + rep + ori.Substring(start+rep.Length);
Thoughts? Comments? Suggestions?
Thanks,
Bob
This should work for you. Added the alternative comma style as well.
var names = "Bob, George, Will, Terry";
var lastCommaPosition = names.LastIndexOf(',');
if (lastCommaPosition != -1)
{
names = names.Remove(lastCommaPosition, 1)
//.Insert(lastComma, " and");
.Insert(lastCommaPosition, ", and");
}
Console.WriteLine(names);
You can use a combination of LINQ and String.Join. This solution does not need the last index of a comma and is "more fluent" to read.
var list = new List<string> { "Bob", "George", "Will", "Terry" };
var listAsString = list.Count > 1
? string.Join(", ", list.Take(list.Count - 1)) + " and " + list.Last()
: list.First();
You can use Linq,
list.Select(i => i).Aggregate((i, j) => i + (list.IndexOf(j) == list.Count -1 ? " and " : " , ") + j);
Hope helps,
This should do the trick for you:
var foo = "Bob, George, Will, Terry";
if (foo.Contains(",")) {
foo = foo.Substring(0, foo.LastIndexOf(",")) + " and" + foo.Substring(foo.LastIndexOf(",")+ 1);
}
I'm not sure what you wanted to do, but the following code works:
string original = "(Bob, George, Will, Terry)";
string result = "";
string[] splited = original.Split(',');
for (int i = 0; i < splited.Count(); i++)
{
if(i == splited.Count() - 2)
{
result += splited[i] + " and";
}
else if(i == splited.Count() - 1)
{
result += splited[i];
}
else
{
result += splited[i] + ",";
}
}
I Used split to split the original string in a vector so i worked with this vector to replace the last comma to the word "and".

Looping through a dataset

I'm looping through the rows and columns of a DataSet to write to a text file with a pipe delimiter. I have it working except I need to leave off the pipe from the last column. Is there a way for me to adjust the loop to loop through fields.count-1 and then refer to the last field outside of the loop?
foreach (object item in row.ItemArray)
{
d = d+ item.ToString() + "|";
}
You can join the contents of any IEnumerable (including arrays) using String.Join, eg:
var newText = String.Join("|",row.ItemArray);
You can use TrimEnd(Char[]) method like
d.TrimEnd(new char[]{'|'});
You can use Linq Aggregate:
d = row.ItemArray.Aggregate((x, y) => x.ToString() + "|" + y.ToString());
You can use:
string.Join("|", row.ItemArray);
You can just use the string.Join method, as follows:
string.Join("|", row.ItemArray);
However, if you're doing other logic in the foreach loop as well, consider using a StringBuilder instead. This has huge performance gains over concatenating a string over and over again. Then, you can simply trim off the final pipe by adjusting it's length.
var d = new StringBuilder();
foreach (object item in row.ItemArray)
d.Append(item.ToString()).Append("|");
d.Length -= 1;
after the loop:
d = d.remove(d.Count()-1);
This will remove the last character of your string.
for(int i = 0; i < row.ItemArray.Length; i ++)
{
if(row.ItemArray[i] == row.itemArray[row.itemArray - 1])
{
d = d+ item.ToString();
}
else
{
d = d+ item.ToString() + "|";
}
}
Only add a delimiter if your adding another value.
for(int i = 0; i < row.ItemArray.Length; i ++)
{
if( d.length == 0)
{
d = item.ToString();
}
else
{
d = d + "|" + item.ToString();
}
}

Getting only the last entry on counting

I'm only getting the last entry of the counting typed like this
public string ZodziuSkaiciavimas()
{
foreach (var sentence in Sakiniai.TrimEnd('.').Split('.'))
{
Rezultatas=(eilute.ToString() + " sakinyje zodziu:" + (sentence.Trim().Split(' ').Count() + sentence.Trim().Split('-').Count() + sentence.Trim().Split(';').Count() + sentence.Trim().Split(':').Count() + sentence.Trim().Split(',').Count() - 4));
eilute++;
}
return Rezultatas;
And I need to get the answer with a return type.
If I type code like this than i get what i want,but no returns.
public string ZodziuSkaiciavimas()
{
foreach (var sentence in Sakiniai.TrimEnd('.').Split('.'))
{
Console.WriteLine(eilute.ToString() + " sakinyje zodziu:" + (sentence.Trim().Split(' ').Count() + sentence.Trim().Split('-').Count() + sentence.Trim().Split(';').Count() + sentence.Trim().Split(':').Count() + sentence.Trim().Split(',').Count() - 4));
eilute++;
}
return Rezultatas;
}
Why arent you appending your results as below
Rezultatas +=(eilute.ToString() + " sakinyje zodziu:" + (sentence.Trim().Split(' ').Count() + sentence.Trim().Split('-').Count() + sentence.Trim().Split(';').Count() + sentence.Trim().Split(':').Count() + sentence.Trim().Split(',').Count() - 4)) + "\n";
It looks like you want to return multiple numbers from your method, but Rezultatas is a single string. You can fix it by changing the return type to List<int>, and returning a list:
public List<int> ZodziuSkaiciavimas() {
var Rezultatas = new List<int>()
foreach (var sentence in Sakiniai.TrimEnd('.').Split('.')) {
var res = sentence.Trim().Split(' ', '-', ';', ':', ',').Length;
Rezultatas.Add(res);
}
return Rezultatas;
}
When the callers decide to print the Rezultatas they gets back from your method, they could decide what character to put between the numbers (say, a comma ',') and print it like this:
var numbers = ZodziuSkaiciavimas();
Console.WriteLine(string.Join(", ", numbers));

proper way assign numer to elements in a List Collection

I am looping through a list of elements, and would like to assign a number to where each element resides in the Collection for deletion puposes. My code below, just gives me the count, is there another option to achieve this. Ex.
0 cat
1 dog
2 fish
ect..
foreach (string x in localList)
{
{
Console.WriteLine( localList.Count + " " + x);
}
}
be old school and go back to a standard for loop:
for(int i = 0; i < localList.Count; ++i)
{
string x = localList[i];
// i is the index of x
Console.WriteLine(i + " " + x);
}
If you really want to get fancy, you can use LINQ
foreach (var item in localList.Select((s, i) => new { Animal = s, Index = i }))
{
Console.WriteLine(item.Index + " " + item.Animal);
}
you have to use a for loop or use a separate index:
for(int i = 0; i < localList.Count;i++)
{
Console.WriteLine( i + " " + localList[i]);
}
Depending on the collection type you are using you can use something like
foreach (string x in locallist)
{
Console.WriteLine(locallist.IndexOf(x) + " " + x);
}
regds, perry

Categories

Resources