Question

I have a class for representing a source file and a destination of where it will be copied:

public class SourceDestination
{
    public string Source { get; set; }
    public string Destination { get; set; }
}

I created a list of SourceDestination and I'm attempting to find sub-lists from this list where multiple source files go to the same destination and multiple destinations receive the same source files.

For example, if file A and B go to destination C, D and E and file F and G go to destination C and D, then A, B, F and G share two of the same destinations, C and D.

Since the SourceDestination class is a source and destination pairing, how would I achieve this sort of set operation in Linq?

I have tried using GroupBy to group the common sources and destinations, but it doesn't seem to achieve the desired effect:

StringBuilder sb = new StringBuilder();
var destinations = _sourceDestinations.GroupBy(sd => new { sd.Destination, sd.Source }).Select(g => g.First()).Select(sd => sd).ToList();

foreach (var destination in destinations)
{
    sb.AppendLine(destination.Source + " : " + destination.Destination);
    sb.AppendLine("");
}
Was it helpful?

Solution

You can use GroupBy to find the moves with a shared source or destination:

var commonDestinations = list.GroupBy(move => move.Destination)
    .Where(group => group.Count() > 1); //not sure if you want this line; you can omit if desired

var commonSources = list.GroupBy(move => move.Source)
    .Where(group => group.Count() > 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top