简体   繁体   中英

C# loop over List<T> collection and find if value exists is saying projectname

I want to see if a value exist in a Collection of properties that I have. Performance is not important.

 //Insert all the main without wav match 
foreach(var mainOnly in fileStuff)
{
    var finalCollection = new FinalFile();

    var result = finalFile.First(s => s.MainId == mainOnly.ParsedName);

    if (string.IsNullOrEmpty(result))
    {
        finalCollection.ClientName = mainOnly.ClientName;
        finalCollection.MainId = mainOnly.ParsedName;
        //finalCollection.WavName = Convert.ToInt64(wav.ParsedName);
        finalCollection.LastWriteTime = mainOnly.CreationTime;
        finalCollection.folder = mainOnly.FolderName;
        mainAll.Add(finalCollection);
    }         
}

I'm looping over a 1,000 records and I don't want to add in another loop, so I figured I would

  1. check to see if s.MainId == mainOnly.ParsedName eg 34343 == 23445
  2. if ( nothing returns ) then add to my new collection

Problem

// what am i doing wrong here?  It is not right 
var result = finalFile.First(s => s.MainId == mainOnly.ParsedName);

// this is not right as it won't compile as "result" = 'ConAppFolderFileFinder.FinalFile'
// that is my projectname.FinalFile   :/
if (string.IsNullOrEmpty(result))

I guess you will just check if your query even returns any element, so you can use this approach:

if(finalFile.Any(s => s.MainId == mainOnly.ParsedName))
{
    finalCollection.ClientName = mainOnly.ClientName;
    finalCollection.MainId = mainOnly.ParsedName;
    //finalCollection.WavName = Convert.ToInt64(wav.ParsedName);
    finalCollection.LastWriteTime = mainOnly.CreationTime;
    finalCollection.folder = mainOnly.FolderName;
    mainAll.Add(finalCollection);
}

Any will just check if there´s at least one element in your collection satisfying your codition and if so it returns true .

If you also need the values of the first element matching the condition you should however use FirstOrDefault as suggested in the comments which will return null if no element was found. However you have to ask for its string-representation (if you overrided ToString ) or any property within ConAppFolderFileFinder.FinalFile which has type string .

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