Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query over a list of Bool+String pairs. How to join strings without foreach?

having some doubts with LINQ queries over objects...

I have this filter descriptions which I want to keep private, and at given checkpoints in the code, I set some flags active. At the end of processing, I want to filter the active flags.

If any flags are active, I want to write them to the console. (I want all flagged checkpoints in one string so I can perhaps change the code to throw an exception instead later on).

This is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace checkpoints
{
    public class Program
    {
        public static void Main(string[] args)
        {            
            var filters = new Filters().FilterList;

            filters[0].flag = true;
            filters[2].flag = true;

            var query = filters.Where(f => f.flag).Select(f => f.desc); 
            Console.WriteLine("Filter points active: ");
            string fpoints = System.String.Empty;

            foreach(string fp in query)
                { fpoints = fpoints + fp + System.Environment.NewLine; }

            Console.WriteLine(fpoints);
        }
    }
    public class Filters
    {        
        public List<Filter> FilterList = new List<Filter>{};

        public Filters()
        {
           foreach(var def in Filters.def_desc)               
               { this.FilterList.Add(new Filter(false, def)); }
        }

        private readonly static string[] def_desc = new string[3]
        { "Filter AX2123: Failed file write.", 
          "Filter XVB231: Failed table load.", 
          "Filter FZD358: Transaction halted." };

        public class Filter
        {
            public bool flag;
            public readonly string desc;       

            public Filter(bool flag, string desc)
            {
                this.flag = flag;
                this.desc = desc;
            }
        }            

    }
}

It works. My issue is with the need to run a for each over the LINQ query results (which is a IEnumerable<Filter> I guess) in order to extract the strings. If I already run a query (i.e., went all over the code) why do I need to "run again"? Looks like it scales terrible and is not very elegant... Any thoughts?

like image 385
Ren85 Avatar asked Feb 23 '23 02:02

Ren85


1 Answers

string fpoint=query.Aggregate((c, c1) => c + System.Environment.NewLine+ c1 );
like image 70
Sleiman Jneidi Avatar answered Feb 25 '23 14:02

Sleiman Jneidi