簡體   English   中英

linq比較列表之間的值 <usertypeclass> 並列出 <string>

[英]linq to compare the values between list<usertypeclass>and list<string>

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

但它給了我錯誤....請回復並建議我哪里出錯了

提前致謝

聽起來你只需要一個加入:

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;

暫無
暫無

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

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