LINQ 来比较 List 和 List 之间的值

本文关键字:List 之间 String UserTypeClass 比较 LINQ | 更新日期: 2023-09-27 18:36:01

我是 LINQ 新手我想编写 linq 来获取 list <usertypeclass>list <string> 之间的值

我有一堂课

public class Hashtable 
        {
             public string Id
            {
                get;
                set;
            }
             public string MediaType 
            {
                get;
                set;
            }
             public string Href 
            {
                get;
                set;
            }
        }

然后我使用这个类在列表中添加值

var list = new List<Hashtable>
{
 new Hashtable { Id = "x001.xhtml", MediaType = "application/xhtm+xml", Href = "text/001.xhtml" },
 new Hashtable { Id = "x002.xhtml", MediaType = "application/xhtm+xml", Href = "text/002.xhtml" },
 new Hashtable { Id = "x003.xhtml", MediaType = "application/xhtm+xml", Href = "text/003.xhtml" }
};

我还有另一个列表,其中包含以下值:

List<string> lstrhtml = new List<string>();
lstrhtml.Add("contents.xhtml");
lstrhtml.Add("x003.xhtml");
lstrhtml.Add("x002.xhtml");
lstrhtml.Add("x001.xhtml");

现在我需要对 linq 进行右键,将两个列表与 id 值匹配,即例如 x003.xhtml 并提取 href 值,到目前为止我尝试的是:

var val=list.Where(o=>lstrhtml.Contains(o["Id"].ToString()))
             .Select(o=>o["Href"]).ToList();

但它给了我错误....请回复并建议我哪里出错了

提前致谢

LINQ 来比较 List<UserTypeClass> 和 List<String> 之间的值

听起来你只需要一个联接:

var query = from id in lstrhtml
            join hashtable in list on id equals hashtable.Id
            select hashtable.href;
foreach (string href in query)
{
    Console.WriteLine(href);
}

(旁注:如果可能的话,我个人会避免使用这个名字Hashtable,因为许多读者在看到它时会想到System.Collections.Hashtable

基本上你需要在两个列表之间做内部连接,这将为你做任务,而不是包含

var query =
from h in listofHashtable
join s in lstrhtml 
on h.Id  equals s
select h.Href;
相关文章: