Combine 2 lists on items where string matches between lists - c#

I have 2 List<string>s that contain a list of network names.
List<string> nets1 = new List<string>() { "net1", "net2", "net3" };
List<string> nets2 = new List<string>() { "net2", "net3", "net4" };
I want to combine them into a new List<string>, but only where the strings are equal. So my desired result will be of type List<string> and contain ONLY net2 and net3.
I have tried to use Union and Concat but they dont seem to be what I am looking for

What you are looking for is Intersect:
var list = list1.Intersect(list2).ToList();

Hope you are looking for the common elements in both list, you can use Intersect
var commonElements = nets1.Intersect(nets2).ToList();

Related

Can I sort a List<string> by integers inside of them?

For example;
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
When I use
list.Sort();
Output:
1[EMPTY] 10[EMPTY] 11[EMPTY] 12[EMPTY] 2[EMPTY] 3[EMPTY] 4[EMPTY] 5[EMPTY] 6[EMPTY] 7[EMPTY] 8[EMPTY] 9[EMPTY]
I want 1-2-3-4-5-6-7-8-9-10-11-12.
How can i solve this problem?
(Sorry my English is bad :{)
You can use OrderBy. Basically trick is to sort the string so parsing as int. and getting the value till the first occurance of [.
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
list = list.OrderBy(c => int.Parse(c.Substring(0, c.IndexOf('[')))).ToList();

How can I only store the second part of a string in a list?

I have a list Textlist1 that contains only strings. Each item in the list begins with the same text: "sentence.text.", but I only want to store the second part of the string in another list, I don't want to store the first part "sentence.text." in the list Textlist2.
For example:
List<string> Textlist1 = new List<string>();
List<string> Textlist2 = new List<string>();
The full strings are stored in Textlist1.
Textlist1[0] = "sentence.text.My name is Fred"
Textlist1[1] = "sentence.text.Jenny is my sister"
How can I only add "My name is Fred" and "Jenny is my sister" to Textlist2?
The result should be like this:
Textlist2[0] = "My name is Fred"
Textlist2[1] = "Jenny is my sister"
See online result: https://dotnetfiddle.net/MpswLZ
List<string> Textlist1 = new List<string>() {
"sentence.text.My name is Fred",
"sentence.text.Jenny is my sister"
};
List<string> Textlist2 = new List<string>();
Textlist2 = Textlist1.Select(item => item.Split('.')[2]).ToList();
You can use Linq. (You need do add using System.Linq)
Textlist2= Textlist1
.Select(i=> i.Substring("sentence.text.".Length))
.ToList();
Split the input strings by the periods, limiting the split to 3. Then take the last entry from the array that split produces.
Textlist2[0] = Textlist1[0].Split('.', 3)[2];
Textlist2[1] = Textlist1[1].Split('.', 3)[2];
You could use Regex.Replace the text.
var regex = new Regex("^sentence.text.",RegexOptions.Compiled);
Textlist2.AddRange(Textlist1.Select(x=>regex.Replace(x,string.Empty)));
The "^" in Regex ensure the required text ("sentence.text") is matched only at the beginning of string and not else where.
Sample Input
Sample Output
List<string> Textlist1 = new List<string>
{
"sentence.text.a",
"sentence.text.b"
};
string prefix = "sentence.text.";
List<string> Textlist2 = Textlist1.Select(x => x.Substring(prefix.Length)).ToList();
https://dotnetfiddle.net/oFhvfs
There are ultimately many ways of doing this, this is just one solution. Which approach you choose depends on how complex the pattern replacement is. I've gone with a simplistic approach as your example is a very simple case.

c# remove everything in List collection after a particular index

I want to be able to remove all elements in a List<string> after a certain index
List<string> s_array= new List<string>();
s_array.Add("a");
s_array.Add("x");
s_array.Add("c");
s_array.Add("y");
s_array.Add("e");
s_array.Add("e");
s_array.RemoveAll(/* what goes here?*/);
What can i put in RemoveAll to achieve this? for example say i wanted to cut out everything from c onwards?
Not sure what all your parameters are, so it's hard to say what approach will be best.
Using RemoveAll(), you could do:
s_array.RemoveAll(x => s_array.IndexOf(x) > s_array.IndexOf("c"));
You could use the key words Take or Skip to help - Example:
var s_array = new List<string> {"a","x","c","y","e","e" };
var sorted = (from x in s_array orderby x select x);
var first3 = sorted.Take(3);
var last2 = sorted.Take(2).Skip(5);

How to append a string in front of all elements in any List<string> in C#

Is there any way I can insert a prefix string "/directory/" in front of all elements in the list ["file1.json", "file2.json"]?
Result I'm looking for would be ["/directory/file1.json", "/directory/file2.json"].
You could use the linq extension method: Select()
List<string> myList = new List<string> { "file1.JSON", "file2.JSON" };
var directory = "/directory";
myList = myList.Select(filename => Path.Combine(directory, filename)).ToList();
This will execute the Path.Combine(directory, filename) foreach item in the list. I'm using the Path.Combine method, because thats the best way to concat directories/filenames, because it should be platform independend.
Try this :
List<string> yourlist = new List<string> { "file1.JSON", "file2.JSON" };
var directory = "/directory/";
yourlist = yourlist.Select(f => string.Concat(directory,f)).ToList();
All the answers using Select are actually creating a new list if you really want to change the values in the existing list then just use a for loop
for(int i = 0; i < fileList.Count; i++)
fileList[i] = #"/directory/" + fileList[i];
You can use the extension method Enumerable.Select. There are two ways of calling Select:
Method syntax
var originalList = new List<string> { "file1.json", "file2.json" };
var list = originalList.Select(e => "/directory/" + e);
Query syntax
var originalList = new List<string> { "file1.json", "file2.json" };
var list = from e in originalList select "/directory/" + e;
Both are the same.
You can use like the following, Which will give you a List as per your requirement:
string stringToappend=#"/Directory/";
List<string> JsonList= new List<string> (){"file1.JSON","file2.JSON"};
var AppendedLis=JsonList.Select(x=> Path.Combine(stringToappend, x)).ToList();
Note :- The LINQ Extension method .Select help you to do this operation, Which will internally iterate through each element in the collection and append the required string with each item and Gives you the List as per your requirements

compare two identical lists of strings

Let's say I have following code:
List<string> numbers = new List<string> { "1", "2" };
List<string> numbers2 = new List<string> { "1", "2"};
if (numbers.Equals(numbers2))
{
}
Like you can see I have two lists with identical items. Is there a way to check if these two lists are equal by using one method?
SOLUTION:
Use SequenceEqual()
Thanks
Use Enumerable.SequenceEqual, but Sort the lists first.
// if order does not matter
bool theSame = numbers.Except(numbers2).Count() == 0;
// if order is matter
var set = new HashSet<string>(numbers);
set.SymmetricExceptWith(numbers2);
bool theSame = set.Count == 0;

Categories

Resources