Linq - get unavailable ids in a list using linq

I have a list ID as "100,1025,5341" and a list of objects. I want to get ids that are not in the list of objects.

suppose the object list contains both 100 and 5341 as a property (for example: ID). I want to get 1025 as a result. I know this query doesn't make sense, but I want to understand it somehow. I can easily use,

string idList = "100,1025,5341";
var objectList = _dataService.GetData();
var result = objectList.Any(item=> idList.Contains(item.ID));

      

to get the list items that have the given IDs. But I want to get another way. I want to get ids that are not listed.

+3


source to share


2 answers


Use Except

:

var ids= idList.Split(',').Select(int.Parse);
var result = objectList.Where(item=> ids.Contains(item.ID));
var r= objectList.Except(result);

      



If you only want ids that are not included in the object list, you can do the following

 var ids= idList.Split(',').Select(int.Parse);
 var r= ids.Except(ids.Where(i=> objectList.Any(item=> item.ID==i)));

      

+2


source


It will get ids from idList

that are not ids objectList

. If I understood correctly what you want ...



var ids = objectList.Select(x=>x.ID).ToList();
var otherIdsList = idList.Split(',').Select(x=>int.Parse(x)).ToList().Where(x=> !ids.Contains(x)).ToList();

      

+1


source







All Articles