LINQ Task

I have a structure like this:

 public struct MyStruct
 {
     public string Name;
     public bool Process;
 }

And I have myStruct list as follows:

"123", true

"123", false

"234", true

"345", false

"456", true

"456", false

I want to use LINQ to return a list as follows:

"123", false

"234", true

"345", false

"456", false

So basically, I want to get a list of different names ("123", "234", ... etc.) along with a boolean flag, and if the names are repeated, I need to perform an AND operation on the flag.

Is there an easy way to do this with a single LINQ statement?

+3
source share
2 answers
var result = input.GroupBy(e => e.Name)
                  .Select(gr => new { Name = gr.Key,
                                      All = gr.All(e => e.Process) });
+10
source
public struct MyStruct
{
     public string Name;
     public bool Process;
}    

public void LinqCellenge()
{
   var sourceList = Enumerable.Empty<MyStruct>();

    var resultList = sourceList
      .GroupBy(item => item.Name, (name, values) => new MyStruct()
        {
          Name = name,
          Flag = values.All(x => x.Flag)
        });
}
+1
source

Source: https://habr.com/ru/post/1785552/


All Articles