【问题标题】:linq to compare the values between list<usertypeclass>and list<string>linq 比较 list<usertypeclass> 和 list<string> 之间的值
【发布时间】:2012-06-07 07:03:41
【问题描述】:

我是 LINQ 的新手 我想写 linq 来获取 list &lt;usertypeclass&gt; 和 list &lt;string&gt; 之间的值

我有课

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();

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

提前致谢

【问题讨论】:

  • 为什么那个类叫做 Hashtable,而它与哈希表无关。这只会增加混乱。

标签: c# linq list class xamarin.ios


【解决方案1】:

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

var query =
from h in listofHashtable
join s in lstrhtml 
on h.Id  equals s
select h.Href;

【讨论】:

    【解决方案2】:

    听起来你只需要加入:

    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。)

    【讨论】:

    • @shweta 请注意,LINQ 连接通常在设备上失败,并显示“正在尝试 JIT 编译方法...”消息。在模拟器上它们执行得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2022-11-21
    相关资源
    最近更新 更多