I have got a simple question I am having a list:
List<string> test = new List<string> {"one", "two", "three", "four"}
Now I want to take for example value "three" and get all elements after it, so it would be looking like:
List<string> test = new List<string> {"three", "four"}
But we do not know where list end so it can be list of many elements and we can not define end as const.
Is it possible?
It sounds like you're looking for SkipWhile from LINQ:
test = test.SkipWhile(x => x != "three").ToList();
That will skip everything until (but not including) the "three" value, then include everything else. It then converts it to a list again.
Since you assign the filtered list back to initial one, then just remove first items up to "three" one:
int count = test.IndexOf("three");
test.RemoveRange(0, count < 0 ? test.Count : count);
This implementation doesn't create additional list, but modifies existing one.
This might do the trick for you
var list2 = test.Skip(2).Take(test.Count).ToList();
or better
var list3 = test.Skip(2).ToList();
Without LINQ it could be done something like this
List<string> outtest = new List<string>();
bool drty = false;
foreach(string st in test)
{
if(st == "three") //or whatever is the input.
drty = true;
if(drty)
outtest.Add(st);
}
Related
I have two lists, l1 & l2
List<string> l1 = new List<string>();
List<string> l2 = new List<string>();
I want to put string.Empty into both of them in a single go.
We can do for variables like -
string a;
string b;
a = b = string.Empty;
I don't want to create List<List<string>>
Can anyone help me with it? thanks in advance.
I want to put string.Empty into both of them in a single go.
You cannot. You could make them point to the same list, but you cannot add into both lists at the same time. There also is no point to it. You don't gain anything. If you need this for anything but code aesthetics, please open a question containing your reasons to do this, because there is different concepts depending on what you want to achieve with it.
You can initialize the list with an empty string variable.
List<string> l1 = new List<string>() { string.Empty };
or something live this
string[] array = { string.Empty };
List<string> l1 = new List<string>(array);
List<string> l2 = new List<string>(array);
Either way, you will have same or less number of lines of code as you have now.
doing l1 = l2 will not work for Lists but you can do something like this
List<string> l2 = l1.ToList();
You can write a method that adds your item to two lists:
private void AddToTwoLists<T>(List<T> list1, List<T> list2, T item)
{
list1.Add(item);
list2.Add(item);
}
You can call it via
AddToTwoLists(l1, l2, string.Empty);
I don't want to create List<List<string>>
If you have only two lists you could do it without a two-dimensional array, but if you plan to have more of them at some point it would be a more convenient and scalable solution to use an array:
var l1 = new List<string>();
var l2 = new List<string>();
foreach (var list in new[] { l1, l2 })
list.Add(string.Empty);
It allows you to avoid writing Add for each list.
You can of course do something like this:
// Most comparable solution to:
string a;
string b;
a = b = string.Empty;
// is in my opinion this
List<string> list1, list2 = new List<string>(list1 = new List<string>{ string.Empty });
But to be honest I don't get your problem why you would do this.
This code is just creating two lists with one entry. And at the end it's the same result like:
List<string> list1 = new List<string>{ string.Empty }
List<string> list2 = new List<string>{ string.Empty }
Fully working example in dotnet fiddle
I'm fairly new to C#, and i've come across a problem trying to split on list elements.
I have a resource file containing string properties as such:
ResourceFile
ResourceFile
I've collected them in a List as:
public List<String> RawNewsList1 = new List<String>()
{
{Resource.NewsContentAndroid1},
{Resource.NewsMetaAndroid1},
};
I'm trying to split on the semicolons but only get results from my second list item.
My split look like this:
public void FilterRawNews()
{
String[] seperator = { ";;;" };
String[] filteredList1 = { "" };
for (int i = 0; i < RawNewsList1.Count; i++) {
filteredList1 = RawNewsList1[i].Split(seperator, 5,
StringSplitOptions.RemoveEmptyEntries);
}
foreach (String s in filteredList1)
{
Console.WriteLine(s);
}
}
Its only prints:
110
2.8
02-07-2020
What am i doing wrong?
Thanks in advance!
The filteredList1 variable is first filled with data from your the first resource, then at the next loop the variable's content is replaced with the data coming from the second resource.
You can use a List<string> instead that has the AddRange method to continuosly add elements to the list
List<string> filteredList1 = new List<string>();
for (int i = 0; i < RawNewsList1.Count; i++) {
filteredList1.AddRange(RawNewsList1[i].Split(seperator, 5,StringSplitOptions.RemoveEmptyEntries));
}
From this we could simplify the code to one-liner with
filteredList = RawNewsList1.SelectMany(a => a.Split(seperator,5, StringSplitOptions.RemoveEmptyEntries)).ToList();
So, what's happen in that single line? That syntax is used when you work with objects that can be treated as a sequence of data. In this context your array RawNewsList1 is a sequence of data and we can use the IEnumerable extensions brought to us by using the Linq namespace. The SelectMany extension requires a lambda expression ( a => ....) that is used to produce the instructions where each element of the sequence (a) is passed to an expression that returns another sequence of data (the array returned by Split). The sequence returned is accumulated to the sequence produced by the next elements from the original RasNewsList1. Finally the accumulated sequence is materialized with the call to ToList()
You are overwriting filteredList1 in each iteration.
That is why you only get the last result.
Just declare filteredList1 as a list and and use AddRange().
Edit: or use LINQ:
var raw = new List<string>() { "111;;;222", "333;;;444" };
String[] seperator = { ";;;" };
var filterlist1 = raw.SelectMany(r => r.Split(seperator, 5, StringSplitOptions.RemoveEmptyEntries)).ToList();
This question already has answers here:
How to remove the first element in an array? [duplicate]
(4 answers)
Closed 3 years ago.
I have a string[] with the same value but different index or location:
string[] test = {"jane", "joy", "adam", "jane"};
I want to delete the first jane without deleting the last jane:
string[] test = {"joy", "adam", "jane"};
I am using this method to delete:
string[] newTest = test.Where(w => w != test[0]).ToArray();
But that deletes all janes:
string[] newTest = {"joy", "adam"};
You can find index of element first and then remove it from list
something like,
string[] test = {"jane", "joy", "adam", "jane"};
List<string> list = new List<string>(test);
list.RemoveAt(list.FindIndex(x => x == "jane"));
Console.WriteLine(string.Join(",", list));
If you just want to delete first element from an array then there are multiple ways to achieve this,
First :
string[] test = {"jane", "joy", "adam", "jane"};
var result = test.Skip(1);
//If you want to convert it to array then
//string[] result = test.Skip(1).ToArray();
Console.WriteLine(string.Join(",", result));
Second : #Caius suggested
string[] test = {"jane", "joy", "adam", "jane"};
var result = test.RemoveAt(0);
Check index in Where clause,
string[] test = {"jane", "joy", "adam", "jane"};
var result = test.Where((x, i) => i != 0);
POC : .net Fiddle
in my project i using this method to delete
But that's saying "I want a new array where no element is the word "jane" so it removes all of them
Here's one method to remove an arbitrary index from an array using a List:
List<string> l = new List<string>(test);
l.RemoveAt(0);
string[] newTest = l.ToArray();
To be honest, you might be better to avoid using an array all together, and just use a List as your storage device if you need this kind of edit
Consider also the advice found here: Remove element of a regular array
If your question is "I want to remove the first occurrence of jane but not the second", let's find the first jane, then make a new array that excludes it:
List<string> l = new List<string>(test.Length);
bool removing = true;
foreach(string s in test) {
if(removing && s == "jane")
removing = false;
else
l.Add(s);
}
string[] newTest = l.ToArray();
There are other ways; you could indexOf to find the first jane, and then Array.Copy everything up to but not including the first instance, and everything after, not including etc.. This code is fairly self documenting though - iterate the array, looking for jane, if we find her and we're still in removing mode, just turn removing mode off (this jane is then never added it to the list, and turning off the removing flag means we'll certainly add the rest of the names into the list) and carry on processing the rest of the list
Consider how much simpler this code would be though if you were just using a List as your storage container:
test.RemoveAt(test.IndexOf("jane"));
How do I check whether a List contains an element that exists in another List using LINQ in C#? I don't want to use a for/while loop.
So, if List1 has A, B, C and List2 has B, 1, 2, then I would return true.
Try this:
List<string> a = ...
List<string> b = ...
var inComon = a.Intersect(b).Any();
Use Enumerable.Any Method:
List<string> l1 = new List<string> { "1", "2" };
List<string> l2 = new List<string> { "1", "3" };
var result = l2.Any(s => l1.Contains(s));
I'd say the Intersect method (see answer by dasblinkenlight) + Any must work better than Contains + Any. It is definetely better to use Any than Count.
I have a string[] which contains value {"data1","data2","data3"}.
and i have a GenericList which contains
data2
data4
two records
i want to get the common datas which is avail in string[] and the genericList
Have you tried something like
string[] s = {"data1", "data2", "data3"};
List<string> list = new List<string> { "data2", "data3" };
var commonList = list.Intersect(s);
Have a look at Enumerable.Intersect Method (IEnumerable, IEnumerable)
Assuming it's a List<string> and you're using .NET 3.5 or higher, you can use the Intersect method from LINQ to Objects:
var intersection = stringArray.Intersect(stringList);
Note that this will return a lazily-evaluated IEnumerable<string>. If you need it in an array or a list, call the relevant method:
var intersectionArray = stringArray.Intersect(stringList).ToArray();
// or
var intersectionList = stringArray.Intersect(stringList).ToList();
Also note that this is a set operation - so the result will not contain any duplicates, even if there is duplication of a particular element in both the original collections.
Take a look at the Intersect extension method here
string[] c1 = { "data1", "data2", "data3" };
string[] c2 = { "data2", "data4" };
IEnumerable<string> both = c1.Intersect(c2);
foreach (string s in both) Console.WriteLine(s);
Will print data2.