so what im doing currently is
getting the text from a file i.e a .txt
and putting it into an array i.e
whilst comparing the two files and outputting the differences between a and B
string[] linesA = File.ReadAllLines(path\file.txt);
string[] linesB = File.ReadAllLines(path\file2.txt);
IEnumerable<String> onlyB = linesB.Except(linesA);
string[] newstr = new HashSet<string>(onlyB).ToArray();
File.WriteAllLines('C:\path\', newstr);
and lets say the text inside the files includes : i.e
file a:
code(324332): 65dfsdf4fth
code(32342): hdfgvsdfsdgh
code(323462): h29dfs8dh
file b:
code(324332): 65dfsdf4fth
code(32342): hdfgvsdfsdgh
code(323462): h29dfs8dh
code(453453): 8gbhfhk,jv
code(343435): gigdbioyvgi
code(3435343): guidfyvfhs
how would i go about getting the text after :
and removing duplicates
so in the end the output would be
8gbhfhk,jv
gigdbioyvgi
guidfyvfhs
edited:
Kind regards,
Phil
You can browse files and registrars row by row in a list of type "Dictionary .Add (TKey, TValue)" so that you only have the unique values.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=netframework-4.8
To get the text after : you can use the Substring and IndexOf methods, then remove the whitespace at the beginning of your new string with TrimStart. At the end use Concat to combine the two lists and GroupBy to filter out the values that have duplicates:
string[] linesA = File.ReadAllLines(#"C:\file.txt");
string[] linesB = File.ReadAllLines(#"C:\file2.txt");
IEnumerable<string> linesA2 = linesA.Select(x => x.Substring(x.IndexOf(":") + 1).TrimStart());
IEnumerable<string> linesB2 = linesB.Select(x => x.Substring(x.IndexOf(":") + 1).TrimStart());
string[] result = linesA2.Concat(linesB2).GroupBy(x => x)
.Where(g => g.Count() == 1)
.Select(y => y.Key)
.ToArray();
result:
result[0] ="8gbhfhk,jv"
result[1] ="gigdbioyvgi"
result[2] ="guidfyvfhs"
Write the result array to new text file:
File.WriteAllLines(#"C:\file3.txt", result);
Related
My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)
I have a .csv file with a list of abbreviations and their actual meaning e.g.
Laughing Out Loud, LOL
I need to be able to search for an abbreviation in a text box and replace the abbreviation with the actual words. This is what I have attempted so far to understand dictionaries but cannot work out how to read in values from the file.
Dictionary<string, string> Abbreviations = new Dictionary<string, string>();
Abbreviations.Add("Laughing Out Loud", "lol");
foreach (KeyValuePair<string, string> abbrev in Abbreviations)
{
txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
}
You can try this LINQ solution the GroupBy is to handle the case where a key is in a file multiple times.
Dictionary<string, string[]> result =
File.ReadLines("test.csv")
.Select(line => line.Split(','))
.GroupBy(arr => arr[0])
.ToDictionary(gr => gr.Key,
gr => gr.Select(s => s[1]).ToArray());
To check if the abbreviation in the TextBox exists in the Dictionary:
foreach (KeyValuePair<string, string[]> abbrev in result)
{
if (txtinput.Text == abbrev.Value)
{
txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
}
}
You can start by creating a Stream Reader for your file, then looping for all your values in the CSV and add them to the dictionary.
static void Main(string[] args)
{
var csv_reader = new StreamReader(File.OpenRead(#"your_file_path"));
//declare your dictionary somewhere outside the loop.
while (!csv_reader.EndOfStream)
{
//read the line and split if you need to with .split('')
var line = reader.ReadLine();
//Add to the dictionary here
}
//Call another method for your search and replace.
SearchAndReplace(your_input)
}
Then have the implementation of that method, search if the input exists in the dictionary and if it does replace it.
You could use LINQ to put the values of the csv into your dictionary, if that's easier for you.
I'm going to assume that your input file may have commas in the actual text, and not just separating the two fields.
Now, if that were the case, then the standard CSV file format for format the file like this:
Laughing Out Loud,LOL
"I Came, I Saw, I Conquered",ICISIC
However, from your example you have a space before the "LOL", so it doesn't appear that you're using standard CSV.
So I'll work on this input:
Laughing Out Loud, LOL
"I Came, I Saw, I Conquered",ICISIC
"to, too, or two", 2
because,B/C
For this input then this code produces a dictionary:
var dictionary =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select new { abbreviation, actual }
).ToDictionary(x => x.abbreviation, x => x.actual);
You can go one better than this though. It's quite possible to create a "super function" that will do all of the replaces in one go for you.
Try this:
var translate =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select (Func<string, string>)(x => x.Replace(abbreviation, actual))
).Aggregate((f1, f2) => x => f2(f1(x)));
Then I can do this:
Console.WriteLine(translate("It was me 2 B/C ICISIC, LOL!"));
I get this result:
It was me to, too, or two because I Came, I Saw, I Conquered, Laughing Out Loud!
I am new to Linq..
i have List<string> object in my code.. i wanted to make it comma separeted, so i written following syntax
string commaSepNames = string.Join(",",lstNames.select(s=>s+" Customer").ToList());
The above syntax will result in appends with "Customer" in the end of name
with comma separated...
but now i want to Append Number (from 1 to Number of item in List) at the end of "Customer" like following:
John Customer1,
Ghanshyam Customer2,
Ferry Customer3,
... and so on..
how can i achive it in one Syntax line ? without using "for loop" or "foreach loop" ??
Thanks....
Use the overload of Enumerable.Select that gives you the index:
var names = lstNames.Select((s, index) => string.Format("{0} Customer{1}", s, index + 1));
string commaSepNames = string.Join(",", names);
If you are not using .NET 4 you need an array:
string commaSepNames = string.Join(",", names.ToArray());
I have a file with this content :
1,2,3,4,5#
1,2,3,4,5#
How can i read all lines using readline ?the important thing is i need to separate the values in each line ,i mean the first line's values 1,2,3,4,5 should be separated .
Suppose i have an array named myarray that can save all values in first line :the array should be like this :
myarray[0]=1
myarray[1]=2
myarray[2]=3
myarray[3]=4
myarray[4]=5
I am so new in IO in c#
Best regards
Using LINQ you can do:
List<string[]> list = File.ReadLines("YourFile.txt")
.Select(r => r.TrimEnd('#'))
.Select(line => line.Split(','))
.ToList();
File.ReadLines would read the file line by line.
.Select(r => r.TrimEnd('#')) would remove the # from end of the
line
.Select(line => line.Split(',')) would split the line on comma and return an array of string items.
ToList() would give you a List<string[]> back.
You can also use TrimEnd and Split in a single Select statement like below, (it would result in the same output):
List<string[]> list = File.ReadLines("YourFile.txt")
.Select(r => r.TrimEnd('#').Split(','))
.ToList();
Try this
string[] readText = File.ReadAllLines(path);
That will return an array of all the lines.
https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx
You can use a StreamReader to read all the lines in from a file and split them with a given delimiter (,).
var filename = #"C:\data.txt";
using (var sr = new StreamReader(filename))
{
var contents = sr.ReadToEnd();
var myarray = contents.
Split(',');
}
Although I do prefer the LINQ approach answer further up.
I need to read a text file like this
MyItemName = Description # MoreInfo
Now I need to convert this 3 fields in to a table. using the '=' and '#' as pattern.
Just splitting on = and # - this returns and IEnumerable of an anonymous class with the properties you are interested in:
var items = File.ReadAllLines(fileName)
.Skip(1) //Skip header
.Where( line => !string.IsNullOrWhiteSpace(line))
.Select(line =>
{
var columns = line.Split('=', '#');
return new
{
ItemName = columns[0].Trim(),
Description = columns[1].Trim(),
MoreInfo = columns[2].Trim()
};
});
This approach would require the separator tokens to be used as separators exclusively - if they do occur in any of the fields, this will mess up everything and void this approach.
if you really want to use linq for it...
It doesn't look very nice and it doesn't create a table, but you get the point:
from line in File.ReadAllLines(filename)
let eqPos = line.IndexOf('=')
let atPos = line.IndexOf('#')
select new {
Name = line.Substring(0, eqPos).Trim(),
Desc = line.Substring(eqPos + 1, atPos - (eqPos + 1)).Trim(),
Info = line.Substring(atPos + 1).Trim()
}