Andy Donegan
Andy Donegan

Reputation: 915

LINQ Query search List within another List and return value

Hi I am just trying to get the structure correct before re-writing some old Javascript code to C#.

I have a List of CanDetails which I need to be able to search within for a ByteName and get its BytePos value.

I am struggling with the query to be able to pull out BytePos with my linqQuery I am hoping to just be able to get the integer value returned only if possible.

Stripped down example below with my attempt at the LinQ which all works.

Problem is I am returning in my result a CanDetails object and still will need to search within that again to find the BtyePos I am looking for.

Many thanks in advance.

    public class ByteData
{
    public string ByteName { get; set; }
    public int BytePos { get; set; }
}

public class CanDetails
{
    public string CanName { get; set; }
    public int CanID { get; set; }
    public List<ByteData> ByteStuff { get; set; }
    public int[] RawData { get; set; }
}

public class test
{
    public static void Main()
    {
        List<CanDetails> CanIDs = new List<CanDetails>();

        CanIDs.Add(new Models.CanDetails()
        {
            CanName = "test",
            CanID = 11,
            ByteStuff = new List<ByteData>() {
                new ByteData { ByteName = "james", BytePos = 0 },
                new ByteData { ByteName = "bob", BytePos = 1 },
            },
            RawData = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 }
        });

        var linqQuery = CanIDs.Where(o => o.ByteStuff.Any(x => x.ByteName == "james")).Select(x => x.ByteStuff).First();
    }
}

Upvotes: 0

Views: 1177

Answers (2)

Georg Patscheider
Georg Patscheider

Reputation: 9463

Flatten the multiple List<ByteData> using SelectMany into one list. Then select the element you need and access the BytePos. If no matching element is found, return null.

 var linqQuery = CanIDs
     .SelectMany(c => c.ByteStuff)
     .FirstOrDefault(b => b.ByteName == "james")
     ?.BytePos;

C# Fiddle

Upvotes: 1

Shoter
Shoter

Reputation: 1039

The answer to your question is to run this LINQ expression:

var byteData = CanIDs
                .SelectMany(can => can.ByteStuff)
                .FirstOrDefault(byteData => byteData.ByteName == "james");

If you write on output byteData.BytePos then it will print '0' as number.

What's going on inside query?

SelectMany

When I selected ByteStuff from all of your can IDs then you can Imagine that after this statement you are working on collection that is union of all ByteStuff Collections that were inside your list.

FirstOrDefault

I am trying to find object in collection that passes given condition. It returns null if it will do not find any object.

I hope that it is the answer that you were looking for.

Upvotes: 1

Related Questions