简体   繁体   English

C#遍历列表 <T> 收集并查找值是否存在,说明项目名称

[英]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 我正在遍历1000条记录,而我不想添加另一个循环,所以我想

  1. check to see if s.MainId == mainOnly.ParsedName eg 34343 == 23445 检查是否s.MainId == mainOnly.ParsedName例如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 . Any都只会检查集合中是否至少有一个元素满足您的条件,如果满足,则返回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. 如果您还需要匹配条件的第一个元素的值, FirstOrDefault按照注释中的建议使用FirstOrDefault ,如果未找到任何元素,则返回null However you have to ask for its string-representation (if you overrided ToString ) or any property within ConAppFolderFileFinder.FinalFile which has type string . 但是,您必须要求其字符串表示形式(如果您重写ToString )或ConAppFolderFileFinder.FinalFile中具有string类型的任何属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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