简体   繁体   中英

Filtering a list in c#

So i have two lists .One is an Attorney object list and the other is a list with GUID .I am first just filling the GUID list with values and then looping through it and then matching it to the ID field of Attorney object to get the Attorney's with the given ID .

Is there a nicer way than my try to achieve this.

List<Attorney> Attorneys = msg.CaseDocument.Attorneys;
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();

foreach (var s in msg.CaseDocument.Defendants)
{
    AttorneyID.AddRange(s.Attorneys);               

}
foreach (var p in AttorneyID)
{
    var z = Attorneys.FindAll(o => o.AttorneyId == p);
    if (z != null)
    {
        CaseDefendantAtt.AddRange(z);

    }

}

How about...

var caseDefendantAtt = msg.CaseDocument.Attorneys.Where(o =>
        msg.CaseDocument.Defendants.SelectMany(d => d.Attorneys).Contains(o.AttorneyId));

Try this

var allAttorneyIds = msg.CaseDocument.Defendants.SelectMany(x=> x.Attroneys);
var caseDefendantsAtt = msg.CaseDocument.Attorneys.Where(x=> allAttorneyIds.Contains(x.AttorneyId)).ToList();

Maybe you could store your Attorneys in a Dictionary of [Guid, Attorney], then looking for each Guid in Dictionary.

Dictionary<Guid, Attorney> Attorneys = CreateDictionaryFrom(msg.CaseDocument.Attorneys);
List<Attorney> CaseDefendantAtt = new List<Attorney>();
List<Guid> AttorneyID = new List<Guid>();

foreach (var s in msg.CaseDocument.Defendants)
{
     AttorneyID.AddRange(s.Attorneys);               
}

foreach (var p in AttorneyID)
{
     var z = Attorneys[p];
     if (z != null)
     {
         CaseDefendantAtt.Add(z);
     }
 }

It will increase the performance with the x1000 factor. But you should notice that we assume there is only one attorney per Guid. Without using a dictionary, we could improve your search in list seeking for FirstOrDefault instead of FindAll

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