C# 使用 Linq,从另一个 List<int> 中的列表中获取所有项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12597221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:50:55  来源:igfitidea点击:

Using Linq, get all items from list that are in another List<int>

c#linqentity-framework

提问by Ali Issa

I have the following scenario: a list of int: List<int> idsOnly = new List<int>();and another list of object that should bring all items that their ids matching the list idsOnly

我有以下场景:一个 int:List<int> idsOnly = new List<int>();列表和另一个对象列表,该列表应该包含其 ID 与列表 idsOnly 匹配的所有项目

var myList = db.Items.Where(item => idsOnly.Contains(item.ID.Value))
                     .Select(a => new { a.Title })
                     .ToList();

I only need to get the titles from the myList

我只需要从 myList 中获取标题

Any help will be appreciated

任何帮助将不胜感激

采纳答案by cuongle

Your code works but it will create the list of anonymous object, not string type

您的代码有效,但它会创建匿名对象列表,而不是字符串类型

Instead of using (a => new { a.Title }, you just use a => a.Titleif you just only want to get the title:

如果您只想获得标题(a => new { a.Title },您只需使用,而不是使用a => a.Title

var myList = db.Items.Where(item => idsOnly.Contains(item.ID.Value))
                     .Select(a => a.Title).ToList();

回答by Jan P.

var myList =
    (from item in db.Items
    where idsOnly.Contains(item.ID.Value)
    select item.Title).ToList()

回答by Tim Schmelter

You can use a Join

你可以使用一个 Join

var titlesInIdList = from item in db.Items
                     join id in idsOnly
                     on item.ID.Value equals id
                     select item.Title;
var list = titlesInIdList.ToList();

回答by Aghilas Yakoub

You can try with (If problem conversion : Convert to int your Id, if is not of int type)

您可以尝试使用(如果转换有问题:转换为 int 您的 ID,如果不是 int 类型)

var myList = db.Items.Where(item => (idsOnly.Contains(Convert.ToInt32(item.ID.Value)))).Select(a => a.Title ).ToList();

Without conversion

无需转换

var myList = db.Items.Where(item => (idsOnly.Contains(item.ID.Value))).Select(a => a.Title ).ToList();

回答by rahul_k

var Result = (from item in db.Items
                 join id in idsOnly
                 on item.ID.Value equals id
                 select new {item.Title}).ToList(); //Here U can return ToArray or ToList()