What would be the most effective method to check whether a string value from list1 exists in list2?
Pseudo Code example
StringList List1 = {"a", "b", "c", "d"};
StringList List2 = {"d", "c", "b", "a"};
foreach (string a in List1)
{
foreach (string b in List2)
{
if(a==b)
{
WriteLine("match");
}
}
}
This method is far too slow to be the best solution, the platform I am using is BI#, a derivative off C#. Array.Exists does not exist in this current library.
You can use Intersect:
var allIntersections = List1.Intersect(List2);
foreach(string match in allIntersections)
Console.WriteLine(match);
If you just want to know if at least one intersects:
bool anyExist = allIntersections.Any();
Converting the List into a comma deliminated string, allows to use a standard InString function in this case a function called StringContains;
foreach (string a in List1)
{
if(StringContains(a, NewString))
{
WriteLine("Match");
}
}
bool flag= list2.Except(list1).Any();
This will be true if list1 doesn't contains all from list2.
Related
Lets say I have a list of String items in a list like:
"Apple",
"Apricot",
"Banana",
"Blueberry",
"Fig",
"Grape"...
As you see We have a few A items, few B items, then we skip C D and E before picking back up with an F and a G item. I need help figuring out how to traverse this list and Insert an "A" before the A items, then a "B" before the B items, and so on...but the important part is even though there are no C, D, or E items I still need there to be a "C", "D", and "E" inserted? So when printed out to the screen it would look something like this...
"A"
"Apple"
"Apricot"
"B"
"Banana"
"Blueberry"
"C"
"D"
"E"
"F"
"Fig"
"G"
"Grape"
Is there a way to do this with vanilla C#?
Here's how I would do this:
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<string> listOfWords = new List<string>
{
"Appricot",
"Apple",
...
};
foreach (string letter in letters)
{
Console.WriteLine(letter);
List<string> words = listOfWords.Where(word => word[0].ToUpper().Eqauls(letter)).ToList();
words.ForEach(word => Console.WriteLine(word));
}
This would loop through all the letters in letters and print them to the console.
Then it would get all the words in listOfWords where they begin with the letter and print them out.
Hope this helps :)
Ok, this seems really easy.
var yourList = new List<string>() {
"Apple", "Apricot", "Banana", "Blueberry", "Fig", "Grape"
};
yourList
.AddRange("ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray().Select(x => x.ToString()).ToList());
yourList.Sort();
I am sure this can be done in tonne of other better ways but simplest one is-
List<string> prods = new List<string>();
prods.AddRange(new List<string>() {
"Apple",
"Apricot",
"Banana",
"Blueberry",
"Fig",
"Grape"
});
//Considering that the list is already sorted alphabetically
//or you can use prods.Sort();
List<string> newList = new List<string>();
string alphabets = "abcdefghijklmnopqrstuvwxyz";
foreach(char a in alphabets)
{
newList.Add(a.ToString());
foreach (var item in prods)
{
if (item.StartsWith(a.ToString()) || item.StartsWith(a.ToString().ToUpper()))
{
Console.WriteLine($"adding {item} to newlist");
newList.Add(item);
}
}
}
foreach (var item in newList)
{
Console.WriteLine(item);
}
Console.ReadKey();
Please let me know how it works out for you.
My idea is to use a new list (List1) and compare it with another list (List2) and create a new list (List3) that exclude all common elements in both lists and results on the non common elements. The difficult thing (to me) is that List1 and List2 elements are not a true match. List1 elements might be part of List2 elements, but not a truly match. Using exclude does not seem to allow the use of IndexOf to compare the two list elements.
Does anyone have an idea how to achieve this?
Thanks in advance.
Assuming you have List1 and List2. Below is the simplest way to compare elements in two lists.
IList<string> List3 = new List<string>();
foreach (var item1 in List1)
{
foreach(var item2 in List3)
{
if (item1 == item2)
{
List3.Add(item1);
}
}
}
My idea is to use a new list (List1) and compare it with another list
(List2) and create a new list (List3) that exclude all common elements
in both lists and results on the non common elements.
From Comments
I need to compare each element in both lists List1 element exists in
List2 element (both strings).
One of the easiest ways to find unique from two lists
var List1 = new List<string>() { "a", "b", "c", "d" };
var List2 = new List<string>() { "a", "e", "f", "g", "c","z" };
var List3 = new List<string>();
List3.AddRange(List1.Except(List2));
List3.AddRange(List2.Except(List1));
List3.ForEach(l=>Console.WriteLine(l));
How about this:
List commonElements = new List<string>();
foreach (var smallString in SmallList)
{
if (large.Any(x => x.Contains(smallString)))
{
// Add to common elements
commonElements.Add(smallString);
}
}
i have a nested list that contains a set of lists, some of these lists are duplicated, i wanna just make a second list without duplicated lists. i tried this :
List<List<string>> liste1 = new List<List<string>>();
List<List<string>> liste2 = new List<List<string>>();
List<string> l1 = new List<string> { "a", "b", "c" };
List<string> l2 = new List<string> { "h", "x", "g" };
List<string> l3 = new List<string> { "a", "b", "c" };
List<string> l4 = new List<string> { "z", "t", "n" };
liste1.Add(l1);
liste1.Add(l2);
liste1.Add(l3);
liste1.Add(l4);
foreach (List<string> lis in liste1)
{
if(!liste2.Contains(lis))
{
liste2.Add(lis);
}
}
it seems easy but its not working, any help will be appreciated. Thx.
Using Linq, you could achieve this.
You could take help of extension methods and look for SequentialEqual of two lists. If the order is not important use Except extension (something like ...s.Except(x).Any()).
var liste2= liste1.Where((x,i)=> !liste1.Skip(i+1).Any(s=>s.SequenceEqual(x)));
Check this Demo
You are checking for reference equality. Instead of using Contains try this substitution
//if (!liste2.Contains(lis))
if(!liste2.Any(subList => subList.SequenceEqual(lis)))
SequenceEqual is an extension method on IEnumerable<T>. I think you will need a using statement importing the System.Linq namespace.
If you dont want to test that the child lists are not sequence-equal, but set-equal (i.e. order is not important), then consider using an implementation of ISet<T> like HashSet<int> instead of List<int>.
Say I have a list of string
List<string> lst=new List<string>(new string[]{"a","b","c","d"});
I wish to get element from index 0 to index 2 assign it to another List lst1(i.e. the element of lst is {"a","b"}), then remove it from lst (i.e. lst becomes {"c","d"}, what's the quickest way of doing this? I am thinking is there any command like
List<string> lst=new List<string>();
lst1=lst.getElements(1,2);
lst.remove(1,2);
Use GetRange() to copy of a range of elements and RemoveRange() to removes a range of elements.
Example :
List<string> lst = new List<string>(new string[] { "a", "b", "c", "d" });
List<string> lst1 = lst.GetRange(0, 2);
lst.RemoveRange(0, 2);
Good Luck !!
You can use AddRange and RemoveRange:
var range = lst.Take(2);
lst1.AddRange(range);
lst.RemoveRange(0, 2);
Demo: http://ideone.com/1X2cV
I would like to add arrays to a list or multidimensional array (not all at once...). But I dont really understand why this should be that hard.
Lets say I have this:
string[] a = { "h", "b"};
string[] b = { "c", "a", "i" };
string[] c = { "out", "in", "file", "test" };
ArrayList x = null;
x.Add(a); //error: Object reference not set to an instance of an object.
x.Add(b);
x.Add(c);
Can I use instead of the ArrayList maybe
string[,] x = null;
But there is no option to .Add
Lets say I have an unknown amount of string[]´s with an unknown size - how do I add them to a List/multidimensional array? And again: I would like to add these string[]´s one by one. Any ideas?
You are getting an NullReferenceException because your list is not initialized:
string[] a = { "h", "b"};
string[] b = { "c", "a", "i" };
string[] c = { "out", "in", "file", "test" };
IList<string[]> x = new List<string[]>;
x.Add(a);
x.Add(b);
x.Add(c);
This assumes that you are constructing a 2-D structure. If you would like to "flatten" your arrays into a single list of strings, create a list, and use its List.AddRange method instead.
you haven't made an instance of the ArrayList you want to store the string arrays in. Try adding
ArrayList x = new ArrayList();
x.Add(a);
...
...
ArrayList x = null;
x.Add(a);
That would work if:
You create an instance of ArrayList:
ArrayList x = new ArrayList();
all you were doing was to declare a local variable.
You are careful to separate ArrayList.Add from ArrayList.AddRange. The former adds a single object. In your case the first element (after the first Add) would be itself an array. To access the "h" would need x[0][0]. AddRange takes each passed collection element in term and adds it to the collection. Thus getting the "h" would be x[0] and "b" would be x[1].
I think you want:
string[] a = { "h", "b"};
string[] b = { "c", "a", "i" };
string[] c = { "out", "in", "file", "test" };
ArrayList x = new ArrayList();
x.AddRange(a);
x.AddRange(b);
x.AddRange(c);
The keyword null essentially means "no object". Therefore when you write x.Add(a) you are trying to call the Add method on something that isn't there.
You need to initialize your list first, which puts something in the box labelled x:
ArrayList x = new ArrayList();
You can now call x.add(a) and your code will work as expected.
You are missing new for ArrayList so you should do it like this:
ArrayList x = new ArrayList();
x.AddRange(a);
x.AddRange(b);
x.AddRange(c);
You can't can't use array in Add method , you will not get any compile error but then while you will access the object you will get just ToString on type that means if you say:
string[] a = { "h", "b"};
x.Add(a);
and then try to loop through the elements like:
foreach (var item in x)
{
Console.WriteLine(item);
}
you will the result: System.String[] and I hope you don't want that, so you need to use AddRange method which takes an argument of type ICollection, so you say:
x.AddRange(a);
and if you do a loop on array list like:
foreach (var item in x)
{
Console.WriteLine(item);
}
you will get the output,
h
b
One way to do it is:
List<List<string>> list = new List<List<string>>();
list.Add(new List<string>(){
"str1", "str2", "..."
});
be sure to include: using System.Collections.Generic;