SuxoiKorm
SuxoiKorm

Reputation: 179

Comparing Arrays LINQ

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; }
}

Upvotes: 2

Views: 76

Answers (2)

Jonathon Chase
Jonathon Chase

Reputation: 9704

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));

Upvotes: 1

Serega
Serega

Reputation: 650

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

Upvotes: 5

Related Questions