Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I got the following collection:
C#
List<(string, List<string>)> items = new List<(string, List<string>)>
{
    ("col1", new List<string>{"1","2","3"}),
    ("col2", new List<string>{"1","3","4"})
};

I need to transform it into List<string, (bool, bool)>:
C#
{
    ("1", (true, true)),  // (because "1" exists in col2)
    ("2", (true, false)), // (because "2" does NOT exists in col2)
    ("3", (true, true)),
    ("4", (false, true))
}

Could you please advise how to accomplish this in a nice fashion? JOIN statement would be sufficient?

Thank you in advance

What I have tried:

I tried using GroupBy, but its very cumbersome
Posted
Updated 5-May-20 22:17pm
v2

Doing this as a single statement won't be particularly clean, but it can be done:
C#
var result = items.Where(i => i.Item1 == "col1").SelectMany(i => i.Item2)
    .Union(items.Where(i => i.Item1 == "col2").SelectMany(i => i.Item2))
    .Select(key => 
    (
        key, 
        (
            items.Any(i => i.Item1 == "col1" && i.Item2.Contains(key)), 
            items.Any(i => i.Item1 == "col2" && i.Item2.Contains(key))
        )
    ))
    .ToList();
Enumerable.Union Method (System.Linq) | Microsoft Docs[^]
 
Share this answer
 
Comments
TheRealSteveJudge 6-May-20 4:42am    
5*
Maciej Los 6-May-20 6:00am    
5ed!
Try this:
C#
List<(string, List<string>)> items = new List<(string, List<string>)>
{
    ("col1", new List<string>{"1","2","3"}),
    ("col2", new List<string>{"1","3","4"})
};

var result = items
	.SelectMany(x=>x.Item2.Select(y=> Tuple.Create(y, x.Item1)))
	.GroupBy(x=>x.Item1)
	.Select(grp=> new {Item1 = grp.Key, Item2 = items.Select(x=>grp.Any(y=>y.Item2==x.Item1)).ToList()})
	.ToList();

Result:
1, {true, true}
2, {true, false}
3, {true, true} 
4, {false, true}
 
Share this answer
 
Comments
TheRealSteveJudge 6-May-20 4:43am    
5*
Maciej Los 6-May-20 6:00am    
Thank you!
I got the following solution:

List<(string, List<string>)> items = new List<(string, List<string>)>
{
("col1", new List<string>{"1","2","3"}),
("col2", new List<string>{"1","3","4","5"})
};

var distinctIds = items.SelectMany(x => x.Item2).Distinct();

var ids = distinctIds.Select(x => (x, items.First(y => y.Item1 == "col1").Item2.Any(y => y == x), items.First(y => y.Item1 == "col2").Item2.Any(y => y == x))).ToList();

It works, but is it possible to embed this logic into one linq query?
 
Share this answer
 
Comments
Maciej Los 6-May-20 4:19am    
Yes, it is possible. See solution #3 ;)

BTW: your answer is NOT a solution. I'd suggest to delete it to avoid down-voting. Such of content should be posted as a comment or you have to improve your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900