C# subarray of strings with LINQ - c#

I have an array of strings and I have to take only those entries, which
are starting with "81" or "82". I've tried it like this:
var lines = File.ReadAllLines(fileName); // This returns an array of strings
lines = lines.TakeWhile(item => item.StartsWith("81") ||item.StartsWith("82")).ToArray();
but this just doesn't work. It retuns an empty string array.
When I loop through lines with a for-loop and compare everytime
if (!firstline.Substring(0, 2).StartsWith("81")) continue;
and then I take the required entries, it's working just fine.
Any suggestions how to get it right with LINQ?

You need to use Where():
lines = lines.Where(item => item.StartsWith("81") || item.StartsWith("82")).ToArray();
TakeWhile will take sequence until condition becomes false, but Where will continue and find all elements matching the condition.

Related

Comparing 2 string arrays using Linq and Regex for a partial match

I have an array of search words and a second array that needs to be searched, returning true or false depending if any of the strings in the 2nd array contain text from the first. I tried using linq but I can't get it to return true if any of the values in the second array contain more than just those search words. I was thinking of using Regex maybe in combination with the linq query but I'm not sure how that would work. Here is what I was tried
string[] gsdSearchVerbiage =
{
"grade",
"transcript",
"gsd"
};
string[] tableColumns = new string []
{
"maxsgrades",
"somethingElse",
};
bool gsdFound = tableColumns.Any(
x => gsdSearchVerbiage.Contains(x));
This returns false. I understand why it's returning false but I can't figure out how to fix it. If the answer is to use a regular expression I couldn't figure out how to do that over 2 arrays...
Last statement should be
bool gsdFound = tableColumns.Any(
x => gsdSearchVerbiage.Any(y => x.Contains(y)));
since you're trying to know if the current item of tableColumns (x) contains any of gsdSearchVerbiage words (y)

Split string and get all after first ocurrence - c#

I have a collection I want to transform into a dictionary. Here's the code:
myCollection.ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]);
Being the collection something like:
{"a=312d","b=dw234","c=wqdqw3=3")
The problem comes at the third object. As you can see, it has a second equal inside of it. This one, and all the character after it, are also part of the value (in the dictionary it should be c:wqdqw3=3). But, as you can imagine, I'm getting something like this in my dictionary a:312d, b:dw234, c:wqdqw3.
How could you change it so that the value of the dictionary was, for each element of the collection, everything that comes after the first '='?
IndexOf() and Substring() should help here
string[] input = { "a=312d", "b=dw234", "c=wqdqw3=3" };
var result = input.ToDictionary(x => x.Substring(0, x.IndexOf('=')),
x => x.Substring(x.IndexOf('=') + 1));

Sort Array by contains specific char count

I have an array and I want to sort this array by its element' specific character count.
var myNewArray = myArray.ToList().Sort(u => u.Name.Split(' ').Length);
but this does not work at all.
How can I provide the LINQ code for this problem ?
myArray[0] = "word1 word2"
myArray[1] = "word1"
myArray[2] = "word3 word2 word2 word2"
when Apply sort my array element order must be like
myArray[2],myArray[0],myArray[1]
Use:
var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToList();
To count the number of words
User OrderByDescending instead
var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToList();
This will save you producing two in-memory lists as well
Your code will not compile List.Sort modifies the current list in place, it doesn't return a new collection.
Having said that, you need Enumerable.OrderByDescending
sentence which have more words must be top of the array
Since you have an Array to begin with you can simply do:
var myNewArray = myArray.OrderByDescending(u => u.Name.Split(' ').Length).ToArray();
Make sure to include using System.Linq;
(Remove ToArray if you only need an IEnumerable<T>)

Check if Characters in ArrayList C# exist - C# (2.0)

I was wondering if there is a way in an ArrayList that I can search to see if the record contains a certain characters, If so then grab the whole entire sentence and put in into a string. For Example:
list[0] = "C:\Test3\One_Title_Here.pdf";
list[1] = "D:\Two_Here.pdf";
list[2] = "C:\Test\Hmmm_Joke.pdf";
list[3] = "C:\Test2\Testing.pdf";
Looking for: "Hmmm_Joke.pdf"
Want to get: "C:\Test\Hmmm_Joke.pdf" and put it in the Remove()
protected void RemoveOther(ArrayList list, string Field)
{
string removeStr;
-- Put code in here to search for part of a string which is Field --
-- Grab that string here and put it into a new variable --
list.Contains();
list.Remove(removeStr);
}
Hope this makes sense. Thanks.
Loop through each string in the array list and if the string does not contain the search term then add it to new list, like this:
string searchString = "Hmmm_Joke.pdf";
ArrayList newList = new ArrayList();
foreach(string item in list)
{
if(!item.ToLower().Contains(searchString.ToLower()))
{
newList.Add(item);
}
}
Now you can work with the new list that has excluded any matches of the search string value.
Note: Made string be lowercase for comparison to avoid casing issues.
In order to remove a value from your ArrayList you'll need to loop through the values and check each one to see if it contains the desired value. Keep track of that index, or indexes if there are many.
Then after you have found all of the values you wish to remove, you can call ArrayList.RemoveAt to remove the values you want. If you are removing multiple values, start with the largest index and then process the smaller indexes, otherwise, the indexes will be off if you remove the smallest first.
This will do the job without raising an InvalidOperationException:
string searchString = "Hmmm_Joke.pdf";
foreach (string item in list.ToArray())
{
if (item.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
list.Remove(item);
}
}
I also made it case insensitive.
Good luck with your task.
I would rather use LINQ to solve this. Since IEnumerables are immutable, we should first get what we want removed and then, remove it.
var toDelete = Array.FindAll(list.ToArray(), s =>
s.ToString().IndexOf("Hmmm_Joke.pdf", StringComparison.OrdinalIgnoreCase) >= 0
).ToList();
toDelete.ForEach(item => list.Remove(item));
Of course, use a variable where is hardcoded.
I would also recommend read this question: Case insensitive 'Contains(string)'
It discuss the proper way to work with characters, since convert to Upper case/Lower case since it costs a lot of performance and may result in unexpected behaviours when dealing with file names like: 文書.pdf

Split and select specific elements

I have a comma separated string which specifies the indexes. Then I have one more comma separated string which has all the values.
EX:
string strIndexes = "5,6,8,15";
string strData = "ab*bc*dd*ff*aa*ss*ee*mm*jj*ii*waa*jo*us*ue*ed*ws*ra";
Is there a way to split the string strData and select only the elements which are at index 5, 6, 8 or 15. Or will I have to split the string first then loop through the array/list and then build one more array/list with the values at indexes defined by string strIndexes (i.e. 5, 6,7,15 in this example)
Thanks
It's reasonably simple:
var allValues = strData.Split('*')
var selected = strIndexes.Split(',')
.Select(x => int.Parse(x))
.Select(index => allValues[index]);
You can create a list from that (by calling selected.ToList()) or you can just iterate over it.
It depends a bit on the length of the string. If it is relatively short (and therefore any array from "Split" is small) then just use the simplest approach that works; Split on "*" and pick the elements you need. If it is significantly large, then maybe something like an iterator block to avoid having to create a large array (but then... since the string is already large maybe this isn't a huge overhead). LINQ isn't necessarily your best approach here...
string[] data = strData.Split('*');
string[] result = Array.ConvertAll(strIndexes.Split(','),
key => data[int.Parse(key)]);
which gives ["ss","ee","jj","ws"].
call Split(','); on the first string and you get an array of strings, that array you can access by index and the same you can do on the second array. No need to loop array lists.

Categories

Resources