PCG
PCG

Reputation: 65

How read list items in list using linq in C#?

I have the following class

[Serializable]
[DataContract]
public class R_ButterFly_Collection
{
        [DataMember]
        public Int64? CollectionNameID { get; set; }
        [DataMember]
        public string CollectionName { get; set; }
}

I need to read CollectionNameID and CollectionName for given match for collection_name.

This is how I tried for CollectionName :

string CollectionName = ButterFlyList.Where(x => x.CollectionName == butterflyName)

But I need CollectionNameID and CollectionName, how could I do that ?

This is what I want :

Int64 CollectionNameID, CollectionName = ButterFlyList.Where(x => x.CollectionName == butterflyName)

Upvotes: 0

Views: 135

Answers (2)

ABlue
ABlue

Reputation: 673

you can use :

 List<R_ButterFly_Collection> results = ButterFlyList.Where(x => x.CollectionName == butterflyName).ToList();

Upvotes: 2

Bola
Bola

Reputation: 758

Assuming:

var ButterFlyList = new List<R_ButterFly_Collection>()
            {
                new R_ButterFly_Collection()
                {
                    CollectionName="one",
                    CollectionNameID=1
                },
                new R_ButterFly_Collection()
                {
                    CollectionName="two",
                    CollectionNameID=2
                },
                new R_ButterFly_Collection()
                {
                    CollectionName="three",
                    CollectionNameID=3
                }
            };

Then you can use linq and return tuple result:

var results = ButterFlyList.Where(x => x.CollectionName == "one").Select(p => new Tuple<long, string>(p.CollectionNameID ?? 0, p.CollectionName));

Note that you need to handle nullable long for CollectionNameID field.

Upvotes: 0

Related Questions