How to remove all elements that satisfy a criteria in C# collection? - c#

I have a string array:
string[] names;
I want to remove all names that has length less than k. How can I do that? Do I have to convert it back to List<string> ?
Thanks,
Chan

Since a string[] can't change it size you can't remove elements from it. So you need to create a new, smaller array with names.Where(s=>!(s.Length<k)).ToArray().
On List<string> you can remove elements inplace with the RemoveAll(s=>s.Length<k) function.

Using LINQ would be like this
List<String> list1 = new List<string>();
List<String> list2 = list1.Except(list1.Where(c => c.Length < 10)).ToList();

Related

How to efficiently split a string, add it to a List, and convert to a Double?

I have some basic code that does what I want it to do, but I think it can be abbreviated / cleaned up. I am struggling a bit on how to do so, however.
The code reads as follows:
List<string> positions = new List<string>();
List<string> players = new List<string>();
foreach (string element in fractionedList)
{
positions.Add(element.Split(',')[2]);
positions.Add(element.Split(',')[3]);
positions.Add(element.Split(',')[4]);
players.Add(element.Split(',')[5]);
players.Add(element.Split(',')[6]);
players.Add(element.Split(',')[7]);
}
List<double> convertedPositions = positions.Select(x => double.Parse(x)).ToList();
List<double> convertedPlayers = playerss.Select(x => double.Parse(x)).ToList();
For reference, my fractionedList will look something like:
"string0,string1,string2,string3,string4,string5,string6,string7,string8,string9,string10,string11,string12",
"string0,string1,string2,string3,string4,string5,string6,string7,string8,string9,string10,string11,string12",
"string0,string1,string2,string3,string4,string5,string6,string7,string8,string9,string10,string11,string12",
"string0,string1,string2,string3,string4,string5,string6,string7,string8,string9,string10,string11,string12",
So I am trying to split each string instance of the List, get the next three elements, and then add them to a new List and then convert that List to a new List of doubles. I am wondering if there is a cleaner way to handle the Split method. Is there an equivalent to Take()? Also, can this all be done in one List creation, rather than creating a List of strings, creating a List of doubles?
The first thing I would change is to not split your string 6 times for no reason. Split it once and store the result in a variable.
With a little LINQ you could shorten your code:
List<double> positions = new List<double>();
List<double> players = new List<double>();
foreach (string element in fractionedList)
{
string[] elementSplit = element.Split(',');
positions.AddRange(elementSplit.Skip(2).Take(3).Select(x => double.Parse(x));
players.AddRange(elementSplit.Skip(5).Take(3).Select(x => double.Parse(x));
}
What my code does is split your element variable on , like you were doing (now only doing it once). Then using Linq's Take() and Skip() I am selecting the [2,3,4] and [5,6,7] indices and adding them to their respective lists (after parsing to double).
Keep in mind that this code will throw an exception if your string input is something that can not reasonably parse into a double. If you are certain that the input will always be good then this code should get you there the quickest.
This would perform the conversion inline, without the need to store in an initial string list
List<double> convertedPositions = new List<double>();
List<double> convertedPlayers = new List<double>();
foreach (string element in fractionedList)
{
var elements = element.Split(',');
convertedPositions.AddRange(elements.Skip(2).Take(3).Select(x=> Convert.ToDouble(x)));
convertedPositions.AddRange(elements.Skip(5).Take(3).Select(x => Convert.ToDouble(x));
}

Sort a list in c# based on exact match/partial match

I have a list of elements list
1) taymril 6.5% inmatro
2) taymril 11.5% tometo
3) taymril 1.5% romeo
The input string is, for example, taymril 1.5% romeo. How do I sort the above list (15-20 elements but I have written only three as an example) based on a match with the input string? how do I do this in a generic way for all input strings and all elements in the database? any idea?
List<string> listString = new List<string>();
listString.Add("taymril 6.5% inmatro");
listString.Add("taymril 11.5% tometo");
listString.Add("taymril 1.5% romeo");
var list = listString.OrderBy(x => x);
//or
var listd = listString.OrderByDescending(x => x);

Search a part of a List<> based on the indext of a pattern match

I am trying to define a LINQ response to this issue, I have a List<List<string>> and I need to compare the first line of the internal list and return that list based on the match:
List<List<string>> mainList = new List<List<string>>();
List<string>lines = new List<string>();
lines.Add("one");
lines.Add("two");
lines.Add("three");
mainList.Add(lines);
lines=new List<string>();
lines.Add("bus");
lines.Add("clock");
lines.Add("chicken");
mainList.Add(lines);
How do I use LINQ to return the entire list which contains "bus"?
If you want to compare any element in the Sub List then do:
List<string> subList = mainList.FirstOrDefault(r => r.Contains("bus"));
If you only want to compare first element in the Sub List then do:
List<string> subList = mainList.FirstOrDefault(r => r.FirstOrDefault() == "bus");
You could try this one:
var result = mainList.FirstOrDefault(x=>x.Contains("bus"));
The above query will search all the list contained in the mainList and it will return you the first List that contains the string "bus". If there wasn't such a list then you would have gotten a null.

Get first elements of List<string[]> to a string[] using LINQ

I have a list of array of string: List<string[]> myList;
Is there any way to get an array of strings with all the elements string[0]?
Like List myList to string[] where elements are myList[string[0]]
I suppose it´s something like var result = from x in myList .Take(0) select x
And question 2)
is there any way to convert a string[] to string[1,] without a for loop?
Now I do:
for (int i = 0; i < arr.Length; i++)
range[0, i] = arr[i];
I need "this syntax" because I´m exporting columns to excel. And I need an object[,] to do a range.set_Value(Type, object[,]).
string[] result = myList.Select(arr => arr.FirstOrDefault()).ToArray();
Is that what you're looking for?
Take(n) only returns an enumerable with at most n elements, so that's obviously wrong.
From what I gather from your question, this should suffice:
string[] result = (from item in myList select item.FirstOrDefault()).ToArray());
For the first part;
var temp = myList.Select(q => q.FirstOrDefault());
For the second part;
I do not think there is a direct Linq statement to convert a single dimension array to a multi dimension one.

Add contents of arraylist to string array

In for each loop i am adding the contents into ArrayList. Now i need to add (or copy/move) the contents of arraylist into string array.
By string array i mean string[].
let me know if more info required.
thanks!
Use ToArray:
string[] array = (string[])list.ToArray(typeof(string));
I would recommend you use List<string> though, as that's more type safe:
List<string> list = ...
string[] array = list.ToArray();
Use the toArray() method:
ArrayList alist = ...;
String []strArray = new String[alist.size()];
alist.toArray(strArray);
You can use ToArray, which others have posted, but if you want to do some checking on the original list, or modify specific items as they're entered, you can also use something like this:
var myStringArray = new string[ArrayList.Count];
int i = 0;
foreach(var item in ArrayList)
{
myStringArray[i] = item;
i++;
}

Categories