my double data in text file like below:
1.4 2.3 3.4
2.2 2.5 2.5
I want simply read this data from file
and store it in an array.
please help me.
I'm a beginner in C#
You can use LINQ:
double[] numbers =
File.ReadAllLines(path)
.Select(s => double.Parse(s)
.ToArray()
If each line can have multiple numbers, you'll need to split the lines:
double[] numbers =
File.ReadAllLines(path)
.SelectMany(s => s.Split(' '))
.Select(s => double.Parse(s)
.ToArray()
You can also use a normal loop:
List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
numbers.Add(Double.Parse(line));
}
Or, to split them,
List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
foreach(string word in line.Split(' ') {
numbers.Add(Double.Parse(word));
}
}
Consult MSDN with the following pointers...
File class to read the file contents as string
String.Split to split the numbers based on your delimited
and Double.Parse to convert from string into double.
var values = from value in File.ReadAllText("C:\\Yourfilename.txt").Split(' ')
select double.Parse(value);
Try this, it should be somewhat more bulletproof than some of the other answers. It does not check for invalid data entries which can't be parsed correctly.
var doubles = File.ReadAllText(path)
.Split(new[] {" ", "\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => double.Parse(s, CultureInfo.GetCultureInfo("en-US"))).ToArray();
This will work if the doubles are splitted by either a space or a line break. And it also works if there are multiple spaces/line breaks. I live in DK so I have setted the culture info explicit for parsing.
Related
I have a string such as the following:
string a = "foo,,,,,,,bar, baz, qux";
Usually a.Split(",") would be okay to split a string by the comma, but with the above situation it would result in many empty strings due to the commas.
Is there a simple way to split a string by one or many occurrences of the separator, so that the result would be something like ["foo","bar","baz","qux"]?
You can simply use StringSplitOptions to remove the empty results.
In .NET Core, you can pass a single character to string.Split and use StringSplitOptions
var output = a.Split(',', StringSplitOptions.RemoveEmptyEntries);
In .NET Framework, you have to pass the single char in a char array (char[]) like so:
var output = a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
EDIT:
Thanks to #Innat3 and #Fildor for pointing out differences in Core and Framework.
use StringSplitOptions.RemoveEmptyEntries:
var parts = a.Split(new [] {',',' '}, StringSplitOptions.RemoveEmptyEntries)
The unfortunate part in some versions of .NET is that you have to pass an array of delimiters with this method rather than a single delimiter, but the output is what you want.
You can try LINQ
var x = a.Split(",").Select(s=>s.Trim()).Where(x => x.Length > 0);
The a.Split(",") method has an overload that lets you exclude empty elements
a.Split(",", System.StringSplitOptions.RemoveEmptyEntries)
You can use linq:
string a = "foo,,,,,,,bar, baz, qux";
var result = a.Split(',').Where(s => s.Length > 0)
var trimmedResult = result.Select(s => s.Trim())
foreach (var s in result) Console.WriteLine(s); // "foo,bar, baz, qux"
foreach (var s in trimmedResult) Console.WriteLine(s); // "foo,bar,baz,qux"
I have a problem about sorting array after reading all decimal numbers and integers from txt file. The file contains both decimal and integer values.
These values can be splited non-fixed space.
Here is my file like this
-12,56 76
11
-6,5 43
15
...
The result is shown like
-12,56 -6,5 11 15 76 ...
How can I do the process.
You can try Linq, SelectMany since single line can contain several numbers:
var numbers = File
.ReadLines(#"c:\myfile.txt")
.SelectMany(line => line.Split(
new char[] {' ', '\t'},
StringSplitOptions.RemoveEmptyEntries))
.Select(item => decimal.Parse(item)) //TODO: Ensure the correct Culture
.OrderBy(item => item)
.ToArray(); // Let's have numbers as an array
string result = string.Join(Environment.NewLine, numbers);
Please, note StringSplitOptions.RemoveEmptyEntries when Splitting - we remove unwanted empty chunks when processing lines like "-12,56 76"
Edit: If you want to try to detect where do we have and integer and where is decimal:
var numbers = File
.ReadLines(#"c:\myfile.txt")
.SelectMany(line => line.Split(
new char[] {' ', '\t'},
StringSplitOptions.RemoveEmptyEntries))
.Select(item => {
// if we succeed in parsing as int, it's int otherwise - decimal
bool isInt = int.TryParse(item, out var intValue);
return new {
isInteger = isInt,
integerValue = intValue,
decimalValue = decimal.Parse(item) //TODO: ensure right culture
};
}) //TODO: Ensure the correct Culture
.OrderBy(item => item.decimalValue)
.ToArray(); // Let's have numbers as an array
Now if you want integer values:
int[] ints = numbers
.Where(item => item.isInteger)
.Select(item => item.integerValue)
//.OrderBy(item => item) // uncomment, if you want to sort ints
.ToArray();
For decimals:
decimal[] decimals = numbers
.Where(item => !item.isInteger)
.Select(item => item.decimalValue)
//.OrderBy(item => item) // uncomment, if you want to sort decimals
.ToArray();
This answer is mostly the same as Dmitry's, but since it's written and it's slightly different, I figured I share.
Since the file contains both decimal and integer values, and an array can only contain one type, it makes sense to obtain an array of decimal values (since all integers can be converted to a decimal).
To split the file on all whitespace characters, we can pass an empty char[] to the Split method, which allows us to use File.ReadAllText, since it will split on the newline character(s) as well:
var result = File.ReadAllText(#"f:\public\temp\temp.txt")
.Split(new char[] {}, StringSplitOptions.RemoveEmptyEntries)
.Select(decimal.Parse)
.OrderBy(i => i)
.ToList();
It sounds like you want to be able to tell which items are integer values from this array, which we can do using the modulus operator (which returns the remainder of dividing one number by another). If a decimal number divided by 1 has no remainder, then it's an integer, so:
var integerValues = result.Where(item => item % 1 == 0).ToList();
var decimalValues = result.Where(item => item % 1 != 0).ToList();
If I have user input from a text box in c#, and have a CSV file of words for example with user input being: "Wow that's cool LOL" and the CSV file:
LOL Laughing Out Loud
ROFL Rolling On Floor Laughing
How would I compare the input text to find any matches in the file? How would I load the file?
You can do:
string input = "Wow that's cool LOL";
string[] splitArray = input.Split();
bool ifFound = File.ReadLines("yourCVSFilePath.csv")
.Any(line => splitArray.Any(line.Contains));
It is doing:
Split the input into an array of words to be compared individually.
Loads the file line by line (lazy loading)
Compare to see if any words in the split array matches any word in the line.
If you want to perform string comparison ignoring case then you can do:
bool ifFound = File.ReadLines("yourCVSFilePath.csv")
.Any(line =>
splitArray.Any(sa =>
line.IndexOf(sa, StringComparison.CurrentCultureIgnoreCase) > -1));
You can use File.ReadLines to read the lines from the csv file and LINQ to filter them:
string input = "Wow that's cool LOL";
string[] words = input.Split();
char delimiter = '\t'; // for example
IEnumerable<string> matchingLines = File.ReadLines("yourCVSFilePath.csv")
.Where(line => words.Intersect(line.Split(delimiter)).Any())
.ToList(());
The Intersect...Any approach is an optimized version of this alternative query:
......
.Where(line => words.Any(word => line.Split(delimiter).Contains(word)))
I have an external text file which has numbers in it. like 4 54 12 32 separated by spaces.
I want to be able to read all the numbers and add them to a list.
static void Main(string[] args)
{
List<int> numbers;
numbers = new List<int>();
StreamReader file = new StreamReader("C:\\text.txt");
while (!file.EndOfStream)
{
string line = file.ReadLine();
Console.Write(line + " ");
}
}
ReadLine reads the whole line so I cannot separate the individual numbers and convert them to ints and I have tried Read which reads the character code of each number rather than the number itself.
Try Splitting the line by spaces
string [] numbers = file.ReadLine().Split(new char[]{' '},
StringSplitOptions.RemoveEmptyEntries);
Split method of string object ( http://msdn.microsoft.com/fr-fr/library/System.String.Split%28v=vs.110%29.aspx ) is what you're looking for.
This method should help you.
public static IEnumerable<int> ReadInts(string path)
{
var txt = File.ReadAllText(path);
return Regex.Split(txt, #"\s+").Select(x => int.Parse(x));
}
You can use File.ReadAllText method:
var numbers = File.ReadAllText("C:\\text.txt")
.Split()
.Where(x => x.All(char.IsDigit))
.Select(int.Parse)
.ToList();
I have a file consisting of two columns that will be stored as a Dictionary where the first column will be the key, and the second column will be the value. The second column is delimited by whitespace, which may be any amount of spaces or tabs.
How do I store this in my Dictionary with the Split() function?
recipesFile = new StreamReader(recipesRes.Stream);
char[] splitChars = {'\t', ' '};
while (recipesFile.Peek() > 0)
{
string recipesLine = "";
recipesLine = recipesFile.ReadLine();
string[] recipesInLine = recipesLine.Split(splitChars);
recipes.Add(recipesInLine[0], recipesInLine[1]);
}
Thanks
recipesLine.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
Also your code in general can be shortened to
var myDictionary = File.ReadLines(myFileName)
.Select(l => l.Split(new []{'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(a => a[0], a => a[1]);
Since your entries are separated using multiple whitespace characters and Split splits on single characters, you need to remove empty entries. There's a separate String.Split overload for that purpose:
string[] recipesInLine = recipesLine.Split(splitChars,
StringSplitOptions.RemoveEmptyEntries);
firstly, use the file.readlines method. then you can use linq over the lines. http://msdn.microsoft.com/en-us/library/dd383503.aspx
Jon Skeet and Marc Gravell both have good examples on using linq to read files here,
Reading a file line by line in C#.
Then use ToDictionary - Yuriy's answer is a good solution.