1

I have List of Lists or arrays. It contains certain ordered sequences:

0 1 2 3
4 5 6
23 24 25 28

etc.

I want to add another sequence, but only if it's unique (easy) and any of the Lists does not contain it. So for example:

0 1 2

will be rejected, and function will return false, and

9 10

will be accepted, and function will return true.

  • You need to make a start on this, we are not a code writing service I'm afraid. – DavidG Jan 08 '21 at 16:51
  • @MathiasR.Jessen thank you kind stranger! Problem solved. –  Jan 08 '21 at 16:52
  • I didn't mark it as duplicate, but that duplicate link either answers your question or you haven't explained yourself correctly. – DavidG Jan 08 '21 at 16:54
  • Maybe at least show your sample data as `List>` and `List`, and show what you've attempted that's not working. – Rufus L Jan 08 '21 at 17:04
  • What if only some of the members of the list exist in another list (i.e. `{0, 1, 2, 9, 10}`) ? Do you just want to add the unique numbers as a new list (`{9, 10}`), or all of them? Please provide more information. – Rufus L Jan 08 '21 at 17:05
  • What do you mean by. *"but only if it's unique"* – Rufus L Jan 08 '21 at 17:22

1 Answers1

1

If I understand you correctly, you want to search through all the lists in a List<List<int>> to see if any contain a set of numbers, and if none do, then add the numbers as a new list.

One way to do this is using Linq:

public static void AddListIfNotExist(List<List<int>> lists, List<int> newList)
{
    if (lists == null || newList == null) return;

    if (!lists.Any(list => newList.All(item => list.Contains(item))))
    {
        lists.Add(newList);
    }
}

In use it might look like:

var lists = new List<List<int>> 
{
    new List<int> { 0, 1, 2, 3 },
    new List<int> { 4, 5, 6 },
    new List<int> { 23, 24, 25, 28 }
};

var newList1 = new List<int> { 0, 1, 2 };
var newList2 = new List<int> { 9, 10 };

AddListIfNotExist(lists, newList1);
AddListIfNotExist(lists, newList2);
Rufus L
  • 36,127
  • 5
  • 30
  • 43