2

How can I compare to array in linq and get all elements where there is at least one intersection? Example:

selectes = {1,5,7} 
Bands[0].SongsID {1,9} 
Bands[1].SongsID {5,6}
Bands[2].SongsID {4,6}

I need to select Bands[0] and Bands[1]. I tried this:

var selectes2 = Bands.Where(t => t.SongsID.Intersect(selectes));

Bands class:

public class Band
{
    public int ID                { get; set; }
    public string Name           { get; set; }
    public DateTime YearOfCreate { get; set; }
    public string Country        { get; set; }
    public int[] SongsID         { get; set; }
}
4
  • Please change your example to compilable C# code (e.g. what is the type of SongsID?). Consider: What is the return type of Intersect? What type does Where expect the delegate to return? What method will do the conversion? Commented Jun 1, 2018 at 22:41
  • So you want to select any band that has any songID in your selectes list? Commented Jun 1, 2018 at 22:43
  • @NetMage im add Band class Commented Jun 1, 2018 at 22:44
  • @JonathonChase Yes, any band that has SongsID[] in selectes Commented Jun 1, 2018 at 22:45

2 Answers 2

5
var selectes2 = Bands.Where(t => t.SongsID.Intersect(selectes).Any());
Sign up to request clarification or add additional context in comments.

2 Comments

Time complexity is O(N^2), performance would be an issue here
@MrinalKamboj I know that) Of course we can easy get guaranteed complexity O(N log N) if use SortedSet or even O(N) in average if use HashSet. But I think, author of this question was searching for the easiest and shortest solution)
1

Assuming you mean to select any band that has any song ID that matches your list of ids, you could accomplish that with this:

var matchingBands = Bands.Where(band => band.SongsID.Any(selectes.Contains));

1 Comment

Array Contains has time complexity of O(N), same solution would work better by converting int[] to Hashset<int>. This would bring down solution time complexity to O(N) instead of O(N^2)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.