Easy way is to use Linq:
string[] lines = File.ReadAllLines(path);
lines = lines.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
File.WriteAllLines(newPath, lines):
OP:
string[] lines = File.ReadAllLines(path);
lines = lines.GroupBy(x => "Books").Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
File.WriteAllLines(newP
ath, lines):
Was that right
No, it's not right!
Instead of making changes at random (which could take us both all day!) lets look at it logically:
lines.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
lines
a Collection (lists and arrays are both examples of collections)
So we can use a Linq Method to "collect them together" so identical lines are "grouped":
lines.GroupBy(x => x)
The
x => x
is a lambda which uses the line whole line itself as the data to group by.
When can then select only those lines where the number of lines in the group (ie the number of lines that are identical) is greater than one - so just the duplicates:
lines.GroupBy(x => x).Where(g => g.Count() > 1)
Then we select the whole text from the group:
lines.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key);
(The Key to the Group is the value you grouped by)
And convert it into an array:
lines.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
So we can put it back into the
lines
array.
Now, if you had a string like:
string s = "hello, this line is about books with hard back covers.";
How would you find out if it contained your search word?