Search code examples
c#linqgenericsgeneric-list

Send a new list to the result of the LINQ query from the list for C#


I'm creating a generic list from the Class I've created and entering my required data.

    public class GroupList
    {
        public int pertt { get; set; }
        public int pips { get; set; }
        public int[] iVals;

        public GroupList(int PerTT , int Pips , int[] iValues)
        {
            this.pertt = PerTT;
            this.pips = Pips;
            iVals = iValues;
        }

        public override string ToString()
        {
            return $"PerTT: {pertt} Pips: {pips} Values: {string.Join(", ", iVals)}";
        }
    }

I want to enter my data into my mydatalist list derived from this Class and send the LINQ query to the Mylinqresult Generic list and print it correctly and perform mathematical operations.

static void Main(string[] args)
{
    List<GroupList> myDataList = new List<GroupList>
    {
        new GroupList(15, 65, new[] {3, 9, 21, 1, 56}),
        new GroupList(15, 65, new[] {13, 19, 121, 11, 156}),
        new GroupList(10, 19, new[] {23, 29, 221, 12, 562}),
        new GroupList(10, 21, new[] {33, 93, 213, 13, 356}),
        new GroupList(21, 9, new[] {43, 49, 421, 41, 456}),
        new GroupList(21, 19, new[] {35, 95, 216, 17, 56})
    };

    List<GroupList> myLinqResult = new List<GroupList>();
    myLinqResult = from x in myDataList
                   where x.iVals[] >  65
                   select x;
}

I get a compile error when I type the query in this way.

The query can be queried based on the parameters given in the Int32 Array and can be accessed by sending the results to the same format list to print and perform mathematical operations with the data.


Solution

  • If you want to select all the GroupList objects that have an item in their array that's over 65, you can do:

    List<GroupList> myLinqResult = myDataList
        .Where(item => item.iVals.Any(i => i > 65))
        .ToList();
    

    Otherwise, if you're trying to select all items that are over 65 (regardless of which GroupList they belong to), you can do:

    List<int> allItemsOver65 = myDataList
        .SelectMany(item => item.iVals)
        .Where(i => i > 65)
        .ToList();
    

    And finally, if you want to select new GroupList items that match the originals but only contain items in their iVal arrays that are over 65, you could do something like:

    List<GroupList> myLinqResult = myDataList
        .Where(item => item.iVals.Any(i => i > 65))
        .Select(item => 
            new GroupList(item.pertt, item.pips, item.iVals.Where(i => i > 65).ToArray()))
        .ToList();