none
C# how to use LINQ to find a list of items meet the requirements RRS feed

  • Question

  • I have a list of int, see the following code.

    static void Main(string[] args)
    {
        List<int> items = new List<int>();
        items.Add(1);
        items.Add(2);
        items.Add(3);
        items.Add(4);
        items.Add(0);
    }
    
    
    I want to find a subset of the List, it has to meet the following conditions:
    The products of all the members are more than the sum of all the members:
    In my example:
    For the first 3 items, the conditions are not met:
    Item1: 1 = 1;
    Item1 & Item2: 1*2 < 1+2;
    Item1 & Item2 & Item3: (1*2*3) = (1+2+3), it is equal, not more than.
    Item1 & Item2 & Item3 & Item4:
    (1*2*3*4) > (1+2+3+4), since 24 is more than 6, so the first 4 items meet the condition, have to pick up the first 4 items.
    Item1 & Item2 & Item3 & Item4 & Item5:
    (1*2*3*4*0) < (1+2+3+4+0), since 0 is less than 10, so the first 5 items do NOT meet the condition.
    Therefore, the maximum number of items meet the condition is the first 4 items.
    How I can write a function to find the subset of the list using LINQ or anything suitable?
    I am uinsg C# Version 7.3,
    Thanks,

    Thursday, November 8, 2018 3:51 PM

All replies

  • Hi zydjohn,

    Thank you for posting here.

    For your question, I am confused about what you want. Do you mean you want to get the list which meant the requirement? Could you give a simple like the results you want?

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 15, 2018 2:11 AM
    Moderator
  • Hello:

    The answer is simple, like this:

    static void Main(string[] args)
    {
        List<int> qualified_items = new List<int>();
        qualified_items.Add(1);
        qualified_items.Add(2);
        qualified_items.Add(3);
        qualified_items.Add(4);
    }

    How I can write a function to get the List<int> as qualified_items?

    Best Regards,

    Thursday, November 15, 2018 10:03 PM