1

I have a class like the following:

public class MyData
{
    public int Key { get; set; }
    public string MyString { get; set; }
    public bool MyFlag { get; set; }
}

I have a list of these classes:

var data = new List<MyData>();

Which is populated as follows:

data.Add(new MyData() { Key = 1, MyFlag = true, MyString = "Hello" });
data.Add(new MyData() { Key = 1, MyFlag = false, MyString = "Goodbye" });
data.Add(new MyData() { Key = 2, MyFlag = true, MyString = "Test" });
data.Add(new MyData() { Key = 2, MyFlag = false, MyString = "Merge" });
data.Add(new MyData() { Key = 3, MyFlag = false, MyString = "Data" });

What I want is a list as follows:

Key       true       false
1         Hello      Goodbye
2         Test       Merge
3                    Data

I need an anonymous type that reflects the three values above. I found a few posts and articles that seemed to suggest GroupJoin, but I'm unsure how I could use that in this case as it seems to allow joining two separate lists.

2 Answers 2

8

I suggest grouping (by Key property). If you want true and false properties we have to put it as @true and @false since true and false are keywords:

var result = data
  .GroupBy(item => item.Key)
  .Select(chunk => new {
     Key =  chunk.Key,
     @true = chunk.FirstOrDefault(item => item.MyFlag)?.MyString, 
     @false = chunk.FirstOrDefault(item => !item.MyFlag)?.MyString, 
   });
Sign up to request clarification or add additional context in comments.

Comments

0

Please note that I am not in front of a PC right now (so I could not test it), but this should give you an idea at the very least.

data
.GroupBy(x => x.Key)
.Select(
    x => new { 
        Key = x.Key, 
        True = data.SingleOrDefault(y1 => y1.Key == x.Key && y1.MyFlag)?.MyString, 
        False = data.SingleOrDefault(y2 => y2.Key == x.Key && !y2.MyFlag)?.MyString
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.