this code works but only finds one text even tho there is two texts in file,but sometimes there can be more than two.
var d = File.ReadAllLines(filePath);
var t = d.Where(g => g.Contains(cotainstring));
string[] splited;
foreach (var item in t)
{
splited = item.Split(new string[] { cotainstring}, StringSplitOptions.None);
return splited[1];
}
return null;
this is an example file for reading purposes.
"?????????????"
{
"AccountName" "dummy1"
"PersonaName" "imdummy1"
"RememberPassword" "1"
"MostRecent" "0"
"Timestamp" "boring"
"WantsOfflineMode" "0"
"SkipOfflineModeWarning" "0"
}
and
"?????????????"
{
"AccountName" "dummy2"
"PersonaName" "imdummy2"
"RememberPassword" "1"
"MostRecent" "0"
"Timestamp" "boring"
"WantsOfflineMode" "0"
"SkipOfflineModeWarning" "0"
}
but my code only gets dummy1, not dummy2 I want to get dummy one and dummy two.
CodePudding user response:
Because you are exiting from foreach
loop after the first iteration. Instead of returning from foreach loop, store each string into an List<string>
and finally return entire list.
var d = File.ReadAllLines(filePath);
var t = d.Where(g => g.Contains(cotainstring));
//Defin result to store all satisfied strings.
List<string> result = new List<string>();
foreach (var item in t)
{
var splited = item.Split(new string[] { cotainstring}, StringSplitOptions.None);
//Store the string in List, instead of return
result.Add(splited[1]);
}
//Return entire string.
return result;
If above code is written inside function, you need to update the return type of that function from string
to List<string>
CodePudding user response:
You can try using Linq Select
and some kinf of materialization, say .ToArray()
to get a collection of dummies:
var lines = File
.ReadLines(filPath)
.Where(line => line.Contains(containstring)) // original query
.Select(line => line.Split( // Select added
new string[] { containstring },
StringSplitOptions.None))
.Select(items => items[1])
.ToArray();