3

I have a entity like

public class Program
{    
    public int ID { get; set; }
    public bool IsActive { get; set; } 
    public string Title { get; set; }
}

and

public class EMetrics
{
    public int ID { get; set; }
    public bool IsActive { get; set; }
    public string Title { get; set; }
    public List<Program> Programs { get; set; }
}

I have repository method like,

IEnumerable<EMetrics> IEmetricsRepository.GetAllByProgram(params int[] programIds)
{
    var metrics = EntitySet
        .Where(x => programIds.Contains(x.Programs.Select(x => x.ID)))
        .ToList();

        return metrics;
}

[The above code throwing build error]

Here only where I am facing problem to get the EMetrics based on the program Ids array params.

I want list Emetrics which are associated with the program.

2 Answers 2

4

You're incorrectly accessing the same input parameter in your LINQ. It should be refactored by changing your inner Select to use a different parameter:

IEnumerable<EMetrics> IEmetricsRepository.GetAllByProgram(params int[] programIds)
{
    var metrics = EntitySet
        .Where(x => programIds.Contains(x.Programs.Select(y => y.ID)))
        .ToList();

    return metrics;
}
2

So you want to check if all elements of one collection are present in the other. In LINQ that can be done with combination of Except and Any:

var metrics = EntitySet
    .Where(x => x.Programs.Select(p => p.ID).Except(programIds).Any())
    .ToList();

Fyi - your current code is failing because Array.Contains expects a single item, an int in this case, while you are giving it a whole enumerable

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.