How to Loop Through a List<T> and Grab Each Item

How can I loop through a ListT and grab each item?

foreach:

foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}

Loop through properties and set the value of each property as an item in a list, print the list and then set the value again? C#

Just as @Camilo Terevinto said you need too take the List instantiation out of the loop

    if (lists.Date.Count() == 0)
{
message = "There Have Been No Merged Pull Requests In This Repository";
}
else
{
PullRequests = new List<PullRequestDetails>();
for (int i = 0; i < lists.Date.Count(); i++)
{
PullRequests.Add(new PullRequestDetails()
{
Title = lists.ShortRequestTitle[i],
Name = lists.Name[i],
Date = lists.Date[i],
CommitLink = lists.ShortCommitList[i]
});
};
}

How to loop through an object list which has a list of the same type and add each object to TreeView?

I have found out a way myself to do this in 11 lines...

public static TreeNode ToTreeNode(Node root)
{
var treeNode = new TreeNode(root.Name);

foreach (var node in root.Children)
{
treeNode.Nodes.Add(ToTreeNode(node));
}

return treeNode;
}

Process a list with a loop, taking 100 elements each time and automatically less than 100 at the end of the list

You can make use of LINQ Skip and Take and your code will be cleaner.

for (int i = 0; i < listLength; i=i+100)
{
var items = bigList.Skip(i).Take(100);
// Do something with 100 or remaining items
}

Note: If the items are less than 100 Take would give you the remaining ones.

Iterate through list of items to their parent and parent to parent level

Ok finally got it working with correct logic, working code as below

class Program
{
static void Main(string[] args)
{
int productId = 6;
var products = GetProducts();
var product = products.FirstOrDefault(p => p.ID == productId);

var output = GetProductRecursively(products, productId, string.Empty);
Console.WriteLine(output);
Console.Read();
}

public static string GetProductRecursively(List<Product> products, int Id, string output)
{
var product = products.FirstOrDefault(p => p.ID == Id);
StringBuilder stringBuilder = new StringBuilder();
if (string.IsNullOrEmpty(output))
output = stringBuilder.Append($"ParentCategoryID={ product.ParentID}, Name={ product.ItemName}, Keywords=").ToString();
if (string.IsNullOrEmpty(product.Category))
{
return GetProductRecursively(products, product.ParentID, output);
}
else
output += $"{product.Category}";
return output;
}
public static List<Product> GetProducts()
{
var products = new List<Product>();
products.Add(new Product { ID = 1, ParentID = -1, ItemName = "Chai", Category = "Breweries" });
products.Add(new Product { ID = 4, ParentID = -1, ItemName = "Mouse-pad", Category = "Electronic" });
products.Add(new Product { ID = 3, ParentID = 1, ItemName = "GST", Category = "Taxes" });
products.Add(new Product { ID = 2, ParentID = 1, ItemName = "Spices" });
products.Add(new Product { ID = 5, ParentID = 4, ItemName = "Mobile" });
products.Add(new Product { ID = 6, ParentID = 3, ItemName = "My Tax" });
return products;
}
}

public class Product
{
public int ID { get; set; }
public int ParentID { get; set; }
public string ItemName { get; set; }
public string Category { get; set; }
}

Looping with foreach through list, to execute code for distinct values

Is there an id column in your datatable as shown above? would your column zero not be taking an id there?

foreach (DataRow dr in ds.Tables[0].Rows {

PaidTrips.Add(new PaidTrip {

LicenseHolderID = dr[0].ToString(),
Value1 = (decimal)dr[1],
Value2 = (decimal)dr[2],
Value3 = dr[3].ToString(),
});

If your grouping by LicenseHolderID your selecting the first element of the grouped result. Is that intended?

List<PaidTrip> paidTrip = PaidTrips
.GroupBy(p => new {p.LicenseHolderID})
.Select(g => g.First())
.ToList();

This would essentialy return one new Object Containing multiple Paid Trip objects containing the same LicenseHolderID.

Usually if you want to use the string name of the group you can reference the key value.

paidTrip.Key.ToString();

might be better to use,

    var paidTrip = PaidTrips
.GroupBy(p => new {p.LicenseHolderID})
.ToList();

foreach (var tripFound in paidTrip)
{
string tripId = tripFound.Key.ToString();
//Generate your PDF File.
}

This should give you one file per group. Apologies if i've picked you up wrong.

Loop through very large Liststring with over 4 million entries in C#

Disclaimer: I haven't looked at the word list-it didn't load on my cellphone. I imagine, from the comments, it's like a csv list of 4 million "words"; the sort of "words" you might see if you had a million monkeys bashing on a million typewriters, probably because that's some corollary to how they were actually generated /p>

In the comments you seemed to indictate that the words in the input string are separated by spaces otherwise they don't show up as emojis. As such I'd load the 4 million exclusions into a hashset, split the string into words, remove words in the hashset then recombine the result:


private static HashSet<string> excludes = new HashSet<string>(); // --> 4 million entries, load it once

string message = "Hello, how are you this fine day?\r\nMy name is SO."; // User input

var bits = input.Split(' ');

for (int x = 0; x < bits.Length; x++)
{
if (exclude.Contains(bits[i]))
{
bits[i] = null;
}
}

var result = string.Join(" ", bits);

This just splits on space, then it knows it can recompose it using space. If your input will have other characters (I can see you have an \r\n there which would defeat this) then you probably want to look at splitting but keeping the delimiters so that you can get your split tokens, replace some, then do a string.Concat instead of join. If you want to wring every last millisecond out of it, then you probably need to look at shifting the solution to Spans but this simple start might provide you with something to investigate whether it's an avenue worth pursuing.

All in I think it's important to tokenize your input and then check entries in their entirety rather than just perform naive repeated replacements, because if your word list contains "hel", "lo", "orl" and "wd" then "hello world" will be reduced to just the separating space even though it contains none of those words. This is because eg replacing "orl" in "world" with nothing creates "wd" which never existed. Also important to note that if the replacements were performed in a different order you'd get a different result ("hello" would disappear but "world" would become "wd" if the "orl" replacement was done last)

Worth noting that hashset is by default case sensitive. do t think you said whether your LULwuts are case sens or not. If they're not, make the hashset case insens

Iterating through a list with out using ForEach loop

You can use String.Join to concatenate all lines:

string lines = string.Join(Environment.NewLine, list);
Console.Write(lines);


Related Topics



Leave a reply



Submit