[英]How to get rows from a list containing each couple of value in LINQ?
我有一個具有以下結構的“夫婦”列表
public class Couple
{
public string Code;
public string Label;
}
還有另一個類似的“東西”列表
public class Stuff
{
public string CodeStuff;
public string LabelStuff;
public int foo;
public int bar;
//etc...
}
我想獲取所有Stuff對象,其中List<Couple>
中的每個對(代碼,標簽)與List<Stuff>
(CodeStuff,Label,Stuff)匹配。
例如夫妻
Couple c = new Couple { Code = "ABC", Label = "MyLabel1" };
將僅與來自的第一行匹配
Stuff s1 = new { CodeStuff = "ABC", LabelStuff = "MyLabel1" }; // OK
Stuff s1 = new { CodeStuff = "ABC", LabelStuff = "MyLabel2" }; // NOT OK
Stuff s1 = new { CodeStuff = "DEF", LabelStuff = "MyLabel1" }; // NOT OK
我嘗試使用.Where
子句或.Foreach
但是我不知道如何將這對夫婦(Code,Label)在一起。 你能幫助我嗎 ?
您需要使用linq join。
List<Couple> lstcouple = new List<Couple>();
List<Stuff> lstStuff = new List<Stuff>();
var result = (from s in lstStuff
join c in lstcouple on new { CS = s.CodeStuff, LS = s.LabelStuff } equals new { CS = c.Code, LS = c.Label }
select s).ToList();
您嘗試過加入嗎? 可能需要調整,但是作為一個主意:
var joined = from c in couplesList
join s in stuffList on c.Code equals s.CodeStuff
where c.Label == s.LabelStuff
select s;
嘗試這個:
List<Stuff> stuffs = new List<Stuff>{s1,s2,s3};
List<Couple> couples = new List<Couple>{c};
var filteredList = stuffs.
Where
(x=> couples.Any(y => y.Code == x.CodeStuff)
&& couples.Any(y=> y.Label == x.LabelStuff)
).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.