mahboub_mo
mahboub_mo

Reputation: 3038

what is the LINQ statement to parse a byte array property of a list and copy the result in another list?

I have an AObject and a BObject that are defined like below

public class AObject {
     public byte[] Types;
     public string FirstProp;
     public string SecondProp;
}
 
 public class BObject {
     public int Type;
     public string FirstProp;
     public string SecondProp;
}

and now i have a list of AObject that i need to copy in BObject but Types property of AObject should be distribute in BObject List;

Its a simple sample of the list values:

 AObjects= { new AObject(){ Types= 1010, first="first" ,second="second" }}; 

and BOject list should contains these for rows:

BObjects :

(1 , "first" , "second")

(0 , "first" , "second")

(1 , "first" , "second")

(0 , "first" , "second")

I was wondering what's the best linq query to achieve that?

Upvotes: 0

Views: 132

Answers (2)

CodeFuller
CodeFuller

Reputation: 31282

var BObjects = AObjects.SelectMany(a => a.Types.Select(t => new BObject
{
    Type = t,
    FirstProp = a.FirstProp,
    SecondProp = a.SecondProp
}));

Here for each value in AObject.Types array new instance of BOject is created. FirstProp and SecondProp are justed copied from AObject and Type is filled with current byte value from AObject.Types.

Upvotes: 1

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

You could use Enumerable.SelectMany to solve your problem. Let's say you have an enumerable of AObjects like

List<AObject> aObjects = new List<AObject>()
{
    new AObject()
    {
        Types = new byte[] { 1, 0, 1, 0 },
        FirstProp = "first1",
        SecondProp = "second1" },
    new AObject()
    {
        Types = new byte[] { 0, 1, 0, 1 },
        FirstProp = "first2",
        SecondProp = "second2"
    },
    //...
};

Now you are able to generate an enumerable of BObjects by iterating all bytes of each AObject like

IEnumerable<BObject> bObjects = aObjects.SelectMany(
    a => a.Types.Select(
        b => new BObject()
        {
            Type = b,
            FirstProp = a.FirstProp,
            SecondProp = a.SecondProp
        }));

The result (in this case) contains the 8 items like required:

{ 1, "first1", "second1" }
{ 0, "first1", "second1" }
{ 1, "first1", "second1" }
{ 0, "first1", "second1" }
{ 0, "first2", "second2" }
{ 1, "first2", "second2" }
{ 0, "first2", "second2" }
{ 1, "first2", "second2" }

Upvotes: 1

Related Questions