Home > Software engineering >  Extract common between List<List<string>> and List<string> - C#
Extract common between List<List<string>> and List<string> - C#

Time:11-21

I have a List<List<string>> Full, build up by

for(...){
Full.Add(new List<string>());
Full[ListIndex].Add(string1);
Full[ListIndex].Add(string2);
Full[ListIndex].Add(string3);
...
}

can be read by

string2 = Full[sublistX][element1];

A List<string> Strings contain some of the instance for string2

I want to create a new List<List<string> NewList only contain sublist from Full[sublistX][element1] which equals to any element in List<string>Strings

For example,

List<List<string>> Full will have:
sublist0: "11", "AA", "!!";
sublist1: "22", "BB", "@@";
sublist2: "33", "CC", "##";
sublist3: "44", "DD", "$$";
...
List<string> Strings will have:
"AA", "DD"...

I want the List<List<string> NewList contain:
sublist0: "11", "AA", "!!"; //match "AA"
sublist1: "44", "DD", "$$"; //match "DD"
...

For now, I'm probably doing this in a stupid way (hardcoded)

List<List<string>> Full;
List<string> Strings;
List<List<string>> NewList;

for (int i = 0; i < Full.Count; i  )
{
    if (Strings.Contains(Full[i][4]))
    {
        NewList.Add(new List<string>());
        NewList[ListIndex].Add(Full[i][0]);
        NewList[ListIndex].Add(Full[i][1]);
        NewList[ListIndex].Add(Full[i][2]);
        NewList[ListIndex].Add(Full[i][3]);
        NewList[ListIndex].Add(Full[i][4]);
        NewList[ListIndex].Add(Full[i][5]);
        NewList[ListIndex].Add(Full[i][6]);
        NewList[ListIndex].Add(Full[i][7]);
        NewList[ListIndex].Add(Full[i][8]);
        NewList[ListIndex].Add(Full[i][9]);
        ListIndex  ;
    }
}

My question is: is there a better way to do it?

I think there could be two points that need optimizing:

  1. Avoid using for() to traverse the whole list "Full," especially when "Full" contains a lot of sublists and "Strings" only have little elements.
  2. From the code you can see I now have 10 elements in each sublist, and that could be increased/decreased in the future, but I hard coded the NewList[ListIndex].Add from index 0 to 9. Is there a way to get the counts of sublist elements? So that I can use for(sublist elements count) to add the NewList.

CodePudding user response:

Well, you can utilize Linq as follows :

var filteredList = Full.Any(strs => strs.Any(s=> Strings.Contains(s))).ToList();

This will give you a list that includes any list that Full at least has one element contained by Strings list.

CodePudding user response:

List<List<string>> full = ...;
List<string> searchItems = ...;

// only filtering
var result = full.Where(l => searchItems.Any(l.Contains)).ToList();

// also copying
var result = full.Where(l => searchItems.Any(l.Contains)).Select(l => l.ToList()).ToList();
  • Related