webdad3
webdad3

Reputation: 9080

Getting the 1st value in a subset of data

I have a result coming back from a LINQ statement that looks like this:

 Id dataId dataVal 
 A  1      1000 
 A  2      2000 
 A  3      3000 
 A  3      3001 
 A  3      3002

What I'd like is to just get the 1st item (dataId = 3 and dataVal = 3000)

Here is my query that is generating the above result:

        var myIds = myList
            .Where(a => ListIds.Contains(a.dataId))
            .Select(x=> new 
            {
                Id = x.Id,
                DataId = x.dataId,
                DataValue = x.DataValue
            }).ToList().Distinct();

Do I need to do some grouping or is there an easier way?

Upvotes: 1

Views: 28

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236288

Group your items by dataId, and then select first item from each group:

var myIds = (from a in myList
             where ListIds.Contains(a.dataId)
             group a by a.dataId into g
             let firstA = g.OrderBy(x => x.DataValue).First()
             select new {
                Id = firstA.Id,
                DataId = g.Key,
                DataValue = firstA.DataValue
             }).ToList();

Or with extension methods (it returns first item in original order):

var myIds = myList
        .Where(a => ListIds.Contains(a.dataId))
        .GroupBy(a => a.dataId)
        .Select(g => new 
        {
            Id = g.First().Id,
            DataId = g.Key,
            DataValue = g.First().DataValue
        }).ToList();

Upvotes: 3

Pat Burke
Pat Burke

Reputation: 590

Use .FirstOrDefault() after the Select

 var myIds = myList
                .Where(a => ListIds.Contains(a.dataId))
                .Select(x=> new 
                {
                    Id = x.Id,
                    DataId = x.dataId,
                    DataValue = x.DataValue
                }).FirstOrDefault();

Upvotes: 1

Related Questions