簡體   English   中英

C#使用LINQ將ID列表與對象列表中的每個ID進行比較

[英]C# compare a list of IDs to each ID in a list of objects using LINQ

我正在嘗試將整數列表與對象列表進行比較。 查看其中一個ID是否與每個對象中的a鍵匹配。 如果是,則返回true,否則返回false。

例如:

List<int> ints = new List<int> () { 1, 2, 3, 4, 5};
List<someObjectType> objects = new List<someObjectType> () { {1, 'one'}, {6, 'six'}, {45, 'forty-five'} };

(x => x.objects.any(a => ints.contains(x.id)));

但是我不知道如何將一個整數列表與一個對象的一個​​屬性進行比較,我只知道如何將整個數組進行比較。

您是否正在尋找類似的東西?

  List<int> ints = new List<int> () { 1, 2, 3, 4, 5};

  // For better performance when "ints" is long
  HashSet<int> ids = new HashSet<int>(ints);

  List<someObjectType> objects = new List<someObjectType> () { 
    {1, "one"}, {6, "six"}, {45, "forty-five"} };

  // if any is matched?
  boolean any = objects
    .Any(item => ids.Contains(item.id));

  // All that match
  var objectsThatMatch = objects
    .Where(item => ids.Contains(item.id));

您的偽代碼幾乎在那里(盡管使用Where而不是Any )...

var objectsWithIds = objects.Where(o => ints.Contains(o.Id));

這讓我懷疑這不是你所追求的...

另一種方法是使用Intersect ,但是您需要將它們都轉換為相同類型的IEnumerable<>

var intersectionOfIds = objects.Select(_ => _.Id).Intersect(ints);

但是,這只會為您提供兩個列表中都包含的Id列表,而不是對象本身,然后需要再次查找它們。

可以使用關鍵字dynamic代替object ,但是更好的解決方案是使用某種靜態類型(如果可能)。

您可以像字典一樣使用dynamic ,添加的鏈接將為您提供一些出色的示例。

我離得很近

(x => x.objects.any(a => ints.contains(a.id)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM