Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an array like this
public List<Application> all_roads = new List<Application>();
And an object with fields:
public string point_of_distination;
public uint length_of_route;
public double price;
public string our_drv_name;
public string our_drv_surname;
public string our_bus_model;
public double gen_ticket_price;
public short cur_year;
public byte cur_day;
public byte cur_month;
public double tour_consumption;
I would like to count general sum of tour_consumption from all objects.
How should I write foreach loop for this ?
Please, help me.
If you only want to calculate tour_consumption you can try this:
var sum = all_roads.Sum(x => x.tour_consumption);
You don't need to select tour_consumption explicitly. You can just pass lambda expression directly to Sum() function.
Please read how LINQ Sum() method works in following article.
Also please make sure that you included System.Linq namespace if you want to consume Sum() method.
double sum = 0;
foreach (var item in all_roads)
{
sum += tour_consumption;
}
Be a lot easier just using Linq:
var sum = all_roads.Sum(x => x.tour_consumption);
If you really wanted to use a for loop:
double sum = 0;
for(var i = 0; i < all_roads.Count; i++)
{
sum += all_roads[i].tour_consumption;
}
or foreach loop
double sum = 0;
foreach (var app in all_roads)
{
sum += app.tour_consumption;
}
Like everyone else said:
double sum = 0.0;
foreach (var app in all_roads)
sum += app.tour_consumption;
You can also check out: https://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx for more info on foreach loops or https://msdn.microsoft.com/en-us/library/bb397687.aspx for more info on Lambda Expressions
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I have a string that contains condition expressions:
"weight=65,age>18"
I want to check if the condition is true.
For example:
int weight = 70;
int age= 19;
string conditions = "weight=65,age>18";
In the above example weight condition is false and age condition is true. Hence the result should be false.
I want to check the condition and return if the condition is satisfied.
You are looking for a parser, as a possible quick solution you can try DataTable.Compute one:
using System.Data;
...
private static T RunWithVariables<T>(
string formula, params (string name, object value)[] variables) {
using DataTable table = new();
foreach (var (n, v) in variables)
table.Columns.Add(n, v is null ? typeof(object) : v.GetType());
table.Rows.Add();
foreach (var (n, v) in variables)
table.Rows[0][n] = v;
table.Columns.Add("__Result", typeof(double)).Expression = formula
?? throw new ArgumentNullException(nameof(formula)); ;
return (T)(Convert.ChangeType(table.Compute($"Min(__Result)", null), typeof(T)));
}
Then
int weight = 70;
int age = 19;
string conditions = "weight=65,age>18";
var result = RunWithVariables<bool>(conditions.Replace(",", " and "),
(nameof(weight), weight),
(nameof(age), age));
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 2 years ago.
Improve this question
I've been looking up a lot of videos, tried using the bubble sort method, insert sort method, but nothing seems to work for this particular problem. I am supposed to add a string (movie name) to an array, but I must do it alphabetically. I can not sort the array after it's completed, it must be done while I add the new strings.
I've seen a lot posts with similar questions like this but all of them sort the array after its completed!
Here is a couple of methods that might help you.
private void PrintAlphabetically()
{
string[] movies = new string[5];
movies[0] = "b";
movies[1] = "x";
movies[2] = "m";
movies[3] = "a";
movies[4] = "t";
AddToStringArray(ref movies, "s");
Array.Sort(movies, (x, y) => String.Compare(x , y));
for (int i = 0; i < movies.Length; i++)
{
Console.WriteLine(movies[i]);
}
}
private void AddToStringArray(ref string[] array, string item)
{
List<string> list = array.OfType<string>().ToList();
list.Add(item);
array = list.ToArray();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have following code in my project
var ReturnStr = Final_BOM.Tables[0].Rows[0]["NEW_BOM_IDS"].ToString();
the above line returns "12,13" but some times only "12"
var ReturnBOM = dsBOMDEfault.Tables[0].Rows[0]["Item_ID"].ToString();
the above line returns "14,15,13".
I want to check ReturnBOM values in ReturnStr
Can any one help how to check
You can use intersect:
Here a quick one-liner:
var results = ReturnStr.Split(',').Select(int.Parse)
.Intersect(ReturnBOM.Split(',').Select(int.Parse))
Demo:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ReturnStr = "12,13";
var ReturnBOM = "14,15,13";
// Convert string to array with Split(',')
// if you dont want int just remove `.Select(int.Parse)`
var ReturnStrElements = ReturnStr.Split(',').Select(int.Parse);
var ReturnBOMElements = ReturnBOM.Split(',').Select(int.Parse);
// Keep only common elements
var results = ReturnStrElements.Intersect(ReturnBOMElements);
foreach(var item in results)
{
Console.WriteLine(item);
}
}
}
We use Split() to convert a string to an array where the delimiter is ','
[Optional] We use Select(int.Parse) to convert each element from string to int.
We use Intersect() to keep only common elements
Use LINQ.
using System.Linq;
The below code will give you an IEnumerable of String with the values you are looking for.
var inBoth = ReturnStr.Split(',').Intersect(ReturnBOM.Split(','))
You may then iterate through the values, cast them to Int32 or do whatever action you want.
If i understanded rights:
string[] returnBomVals = ReturnBom.Split(',');
string[] returnStrVals = ReturnStr.Split(',');
foreach (var vals in returnStrVals)
{
foreach (var strVals in returnBomVals)
{
if (ReturnStr.Equals(vals))
{
//Do Actions
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to do a LINQ expression where the expression varies on how deep the expected node is in the hierarchy.
So I use concat on a string like this:
var parString = string.Concat(Enumerable.Repeat(".SelectMany(f => f.level)", level));
so if its 4 levels deep I get the string :
string1 = ".SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level).SelectMany(f => f.level)"
I then want to use this string in a LINQ expression, example:
List + string1 + .FirstOrDefault(.......);
Is this even possible? How can I do it?
Use a for loop to determine how many times to call .SelectMany:
var query = List;
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level);
}
// Materialize query with `FirstOrDefault` or anything you need
Notice that currently if you reach the maximum depth and still continue you will get an exception. To solve that you can add an if statement to check that f.level is not null or not empty depending on your logic. Something like:
for(int depth = 4; depth > 0; depth--)
{
query = query.SelectMany(f => f.level ?? Enumerable.Empty<YourType>());
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Must be a simple question, and I'm again close to a nervous breakdown because I can't find it:
I have a multimensional List that I defined as an own class (Id, Title, Desc, Start, Length, URL) and that I filled in one function
hyperlist.Add(
new ListElement
{
Id = n,
Title = title,
Desc = desc,
Start = OffsetTotal,
Length = TagLength,
URL = LinkURL
});
I pass it to another function where I have to loop through it and compare each entry of the list to a parameter.
void BuildGList(List<ListElement> LinkList)
{
int startIndex = 5;
foreach (int Id in LinkList)
{
if(startIndex < Start)
{
....
}
}
}
I don't see how to address each single column and googling it I get the impression that nobody uses lists to do what I want here.
-update-
I am asked to clarify my question. Lucky enough it had been clear to the ones that answered it: I didn't know how to refer to a special parameter in a List. Now I know that you can do it with item.parameter.I'm really grateful for the help received in Stackoverflow but sometimes I get the impression that many of you experienced coders have little empathy and understanding for the problems a beginner faces and the effort it takes to google through a jungle of posts. Especially if you are a beginner and therefore sometimes miss the correct keywords. On this one I was busy for an hour and close to a breakdown as I knew I was catching really simple. If you know it then it's always easy. Cheers
You can use foreach like this:
foreach (ListElement item in LinkList)
{
if (item.Length < startIndex)
{
//Do something
}
}
You can filter the list using Linq e.g. to return an IEnumerable as the subset you could do:
private IEnumerable<ListElement> BuildGList(List<ListElement> linkList)
{
int startIndex = 5;
return linkList.Where(element => startIndex < element.Start);
}
You can use takewhile with a foreach if you want to use the list index:
foreach(var item in LinkList.TakeWhile((item, index) => index < startIndex))
{
//enter your code here
}
Also, if you want to compare with a element value inside the list, you can use where with the foreach:
foreach(var item in LinkList.Where(item => item.Start < startIndex))
{
//enter your code here
}