简体   繁体   中英

Getting results from a List<T> C#

I trying to find a code of primitive type inside a List of objects and get the results into a new list.

I've been looking for something like that in Google but everyone talks about intersection between Lists and I want something like this.

            int AssocCode = 2;
            //Entity.ID
            //Entity.Name
            //Entity.AssociationCode
            List<Entity> list = new List<Entity>();
            list.Add(new Entity(1, "A", 1));
            list.Add(new Entity(2, "B", 2));
            list.Add(new Entity(3, "C", 3));
            list.Add(new Entity(4, "D", 2));
            list.Add(new Entity(5, "E", 2));

            /*I want the results for finding that code inside the collection**/
            List<Entity> newList = list .... find/intersect/select/remove/whatever (x => x.AssociationCode = AssocCode);
int associationCode = 1;

List<Entity> newList = list.Where(e => e.AssociationCode == associationCode).ToList();

Worth mentioning that you should only call ToList() if you need the results right away.

This is better if you don't need the results right away.

IQueryable<Entity> entities = list.Where(e => e.AssociationCode == associationCode);

You can then filter further without hitting the database.

应该这样做:

var newList = list.Where(e => e.AssociationCode == AssocCode).ToList()

I solved it 1 minute ago my question. That works like this.

            List<Entity> newList =list.FindAll(item => item.AssociationCode == associationCode)

But now I see your answer PeteGO and I tested and it works also but at the end you new to add this .ToList()

Now I am a little bit confused. What is the different between these 2.

            fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode);
            vs
            fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM