2017-01-02 75 views
0

我有一個列表,其中包含一些屬性和列表。我想根據內部列表我如何使用LINQ 例 列表從列表中選擇不同的數據使用LINQ

{item1 = 1, item2=2,list{a1=l1,a2=l2,a3=l5},item3 =3} 
{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3} 
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3} 
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3} 

我要選擇具有「A1」。如果我的屬性不同值的記錄實現它的屬性來選擇唯一的記錄發現的「A1」重複的值,那麼我將比較值「A3」 =「L5」

預期結果:

{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3} 
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3} 
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3} 
+0

你能提供你的類的結構?我不知道你是如何構建它們的(看起來像是我的詞典) – fharreau

+0

下面的Leppie是類似的結構 – Pavan

回答

0

首先要GROUPBY在你內心的列表A1,然後是分組內選擇對於a3!=「l5」。

List<foo> col = new List<foo>(); 
List<string> tmp = new List<string> {"l1","l2","l5"}; 
col.Add(new foo {item1 = 1, item2=2,lst=tmp,item3 =3}); 
tmp = new List<string> {"l11","l2","l3"}; 
col.Add(new foo {item1 = 21, item2=21,lst=tmp,item3 =3}); 
tmp = new List<string> {"l12","l2","l3"}; 
col.Add(new foo {item1 = 31, item2=22,lst=tmp,item3 =3}); 
tmp = new List<string> {"l1","l2","l3"}; 
col.Add(new foo {item1 = 41, item2=23,lst=tmp,item3 =3}); 

var qry = col.GroupBy(i => i.lst[0]).Select(g => g.Where(j => j.lst[2]!="l5")); 

如果有多個副本在您的A3不是「L5」,你會得到所有的人,所以你可能需要,如果這是不希望對別的東西進行過濾。

+0

嗨吉姆謝謝你的嘗試,但在你的情況下,你正在考慮字符串列表,而在我的情況下,它也是一個對象列表。所以i.lst [index]可能不可能。 – Pavan

+0

在這種情況下,您可以訪問子對象的元素。 –

0
class Log 
{ 
    public int DoneByEmpId { get; set; } 
    public string DoneByEmpName { get; set; } 

    } 

public class Class1 
{ 
    static void Range() 
    { 
     var array = new List<Log>() {new Log() {DoneByEmpId = 1,DoneByEmpName = "Jon"}, 
      new Log() { DoneByEmpId = 1, DoneByEmpName = "Jon" } , 
      new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" }, 
      new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" }, 
      new Log() { DoneByEmpId = 3, DoneByEmpName = "Peter" }}; 

     var ordered = 
      array.GroupBy(x => x.DoneByEmpId).ToList().Select(x => x.FirstOrDefault()).OrderBy(x => x.DoneByEmpName); 
     foreach (var item in ordered) 
     { 
      Console.WriteLine(item.DoneByEmpName); 
     } 
    } 
} 

結果:
喬恩
最大
彼得