0

I have an IEnumerable that returns a list of Processes and details from an SQL stored procedure.

I'm trying to get a list of Distinct values of ProcessQuestions from ProcessList.

I've tried the following code but it always lists everything from ProcessList including duplicate ProcessQuestions.

ProcessListDistinct = ProcessList.Select(p => new ProcessListSummary
            {
                ProcessQuestions = p.ProcessQuestions,
                ProcessQuestionsID = pProcessQuestionsID
            }).Distinct().ToList();

How do I only show distinct values of ProcessQuestions please.

Many thanks

codingitup
  • 149
  • 2
  • 13
  • Would using something like [this](https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property), and doing a distinct on the `ProcessQuestionsID` work? If not, what makes a value of ProcessQuestions unique? – Lolop Mar 30 '21 at 14:42
  • Hi Lolop, Unfortunately that didn't work as it didn't recognize DistinctBy after adding the additional code. The stored procedure returns duplicate ProcessQuestions and I only want to show the distinct ProcessQuestions and not duplicates. – codingitup Mar 30 '21 at 15:07

1 Answers1

0

Refer to this thread.

LINQ's Distinct() on a particular property

What you need is a "distinct-by" effectively.

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

So you can change your code to use DistinctBy.

 var s = ProcessList.Select(b => new ProcessList
        {
            //...
            ProcessListSummary= b.ProcessListSummary.Select(p => new ProcessListSummary
            {
                ProcessQuestions = p.ProcessQuestions,
                ProcessQuestionsID = p.ProcessQuestionsID
            }).DistinctBy(x => x.ProcessQuestions).ToList()
        }).ToList();
Yinqiu
  • 6,609
  • 1
  • 6
  • 14