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
}
}
}
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 2 years ago.
Improve this question
What i want to do is to use something like this Console.Writeline($"Name {Key} - Points: {Value}");
but i dont know how to make the data from the txt into Keys and Values.
I see, you want to fill a Dictionary<string, int> with the names and points of people, right?
If yes then I would suggest never use a dictionary Keys for names, because names are the data that can be duplicate which will eventually lead your software to throw exceptions regarding that.
Make a Generic List of custom class data. Something like this:
public class UserPoint
{
public string Name { get; set; }
public int Points { get; set; }
}
Then like below you can read your text file and load the data into the Generic List.
public static void Main(string[] args)
{
var lines = System.IO.File.ReadAllLines(#"myfile.txt"); // I assume each user info is separated by a newline.
var pointsList = new List<UserPoint>();
foreach(var line in lines)
{
var splittedLine = line.Split(';');
if(splittedLine.Length < 1) continue;
var userPoint = new UserPoint { Name = splittedLine[0].Trim() };
if(splittedLine.Length > 1 && int.TryParse(splittedLine[1].Trim(), out var points)) // updated the direct conversion to safe conversion with tryparse.
{
userPoint.Points = points; // To get rid of extra parsing you can also keep Points property as string.
}
pointsList.Add(userPoint);
}
}
PS: There are multiple other ways to read the text file but I used a simple way, You can also use FileStream and StreamReader classes if you like. Read more on reading text files on these MSDN Articles.
EDIT:
I notice you want to iterate and print through the list as well, you can do in the first loop or you can write a loop again. See:
foreach(var userPoint in pointsList)
{
Console.WriteLine($"Name: {userPoint.Name}, Points: {userPoint.Points}");
}
EDIT 2:
OP has asked to sort the list in descending order based on the points value. Here is a solution for that:
pointsList = pointsList.OrderByDescending(userPoint => userPoint.Points).ToList();
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 5 years ago.
Improve this question
I have a model class called UnicodeMap that I use to represent the hexadecimal unicode value and its consonants and values for Amharic characters.
public sealed class UnicodeMap
{
public string Letter;
public string Consonant;
public string Vowel;
}
I have stored the mapping in CSV and read in runtime to populate a dictionary.
Here is the excerpt of the code that reads and populates the dictionary:
private Dictionary<string, UnicodeMap> _unicodeMap;
void ReadMap()
{
var engine = new FileHelperAsyncEngine<UnicodeMap>();
using (engine.BeginReadFile(MapFile))
{
foreach (var record in engine)
{
_unicodeMap.Add(record.Letter, record);
}
}
}
When I try to get a value from the dictionary using TryGetValue, it always returns false:
public void Translate(string text)
{
var words = text.Split(' ', '.');
foreach (var word in words)
{
var chr = Char.Parse(word);
var unicodeStr = #"\u" + ((int) chr).ToString("X4");
UnicodeMap map;
if (_unicodeMap.TryGetValue(unicodeStr, out map)) //returns false
{
_animator.SetTrigger(map.Consonant);
_animator.SetTrigger(map.Vowel);
};
}
}
For example, when the string is "ሀ", the value of the unicodeStr variable is "\u1200". And I have a string with the value "\u1200" as a key in the dictionary. However, TryGetValue cannot seem to find the key in the dictionary.
How can I solve this issue? What is the possible cause?
Edit: Added a gif of the debugger looking at the values of _unicodeMap dictionary
It's a little hard to see in the gif, but it appears you have a trailing space after the text in the dictionary keys, so you are actually comparing "\u1200" and "\u1200 ".
Fix the way you populate the dictionary by doing a .Trim() on the key.
private Dictionary<string, UnicodeMap> _unicodeMap;
void ReadMap()
{
var engine = new FileHelperAsyncEngine<UnicodeMap>();
using (engine.BeginReadFile(MapFile))
{
foreach (var record in engine)
{
_unicodeMap.Add(record.Letter.Trim(), record); //Added .Trim()
}
}
}
Or fix FileHelperAsyncEngine to not leave the trailing space in the Letter property.
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
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 8 years ago.
Improve this question
Title is like tl;dr version, here is what I mean:
I made currently just a string (to be a file with text), and I am splitting this string into separate words. I would like to make a method that allows me to mark words based on string/file. For example:
string nameOfString = "John likes pancakes";
Categorize(string nameOfString, class nameOfCategory)
this method would make John, likes and pancakes into a category (like Stupid, bestTexts) I passed to nameOfCategory.
I would like to count then the words into all of the categorys, so probably should use some kind of array top do this. Can someone help me with this? The big problem is I really have no idea how to pass the category (as a seperate class or just a string, maybe string[]?) and still be able to count it.
static void Main(string[] args)
{
var inputList = new List<string>
{
"John likes pancakes",
"John hates watching TV",
"I like my TV",
};
var dic = new Dictionary<string, int>();
inputList.ForEach(str => AddToDictionary(dic, str));
foreach (var entry in dic)
Console.WriteLine(entry.Key + ": " + entry.Value);
}
static void AddToDictionary(Dictionary<string, int> dictionary, string input)
{
input.Split(' ').ToList().ForEach(n =>
{
if (dictionary.ContainsKey(n))
dictionary[n]++;
else
dictionary.Add(n, 1);
});
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Improve this question
i have a following data in 3 sets.
EUR5-002,EUR10-000,
EUR20-001,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-000,EUR10-000,
EUR20-002,EUR50-001,
EUR100-001,EUR200-000,
EUR500-000
EUR5-001,EUR10-001,
EUR20-002,EUR50-001,
EUR100-002,EUR200-003,
EUR500-000
Here EUR - CurrencyID and 5,10,20,50,100,200,500 are currency values. And the values after "-" is no of notes of the corresponding denomination.(EUR5-002, means 2 notes of 5 EUROs)
In my code I have read each set as string and added to List.
I need a logic in C# using regex or someother to add each individual denomination count from all 3 sets of data.
From the above data, I have to get the output as below.
EUR5-003,EUR10-001,
EUR20-005,EUR50-003,
EUR100-004,EUR200-003,
EUR500-000
Code does not handles any errors which can be caused by wrong input format, you can maintain it for yourself.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var data = new [] {
"EUR5-002,EUR10-000,EUR20-001,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-000,EUR10-000,EUR20-002,EUR50-001,EUR100-001,EUR200-000,EUR500-000",
"EUR5-001,EUR10-001,EUR20-002,EUR50-001,EUR100-002,EUR200-003,EUR500-000"
};
var results = new Dictionary<string, int>();
foreach (var line in data)
{
var entries = line.Split(',');
foreach (var entry in entries)
{
var parts = entry.Split('-');
string key = parts[0];
if (!results.ContainsKey(key))
{
results[key] = 0;
}
results[key] += int.Parse(parts[1]);
}
}
foreach (var result in results)
{
Console.WriteLine(result.Key + "-" + result.Value.ToString("000"));
}
Console.ReadLine();
}
}
}
You can do it this way
//limit is the highest value of currency
int temp=0;
for(int x=1;x<=limit;x++,temp=0)
{
if((temp=parseDenomination(x,input))!=0)
output+=","+"EUR"+x+"-"+temp;
}
//output has your desired output
private static int parseDenomination(int no,String input)
{
return Regex.Matches(input,#"(?<=EUR"+no+#"-)\d+")
.Cast<Match>()
.Select(x=>int.Parse(x.Groups[0].Value))
.ToList()
.Sum();
}