2012-08-13 20 views
0

我有這個問題的列表,我似乎無法修復它從通用列表中刪除

我有這個類,它實現了具有以下方法的接口。

public List<T> CalculateWad<T, TH>(
    List<T> outputList, 
    List<TH> inputList, 
    bool flag) 
{ 
    ... 
} 

現在,我有一個outputlist,本着共同的場合同inputlist。我需要在outputlist中刪除inputlist中存在的所有合約。

它必須儘可能通用。我似乎無法獲得列表的字段。

任何想法?

+0

您的意思是,在該方法中,您無法訪問例如'outputList [0] .Contract'? – Rawling 2012-08-13 12:34:45

回答

0

因此,這是你的接口:

公開名單CalculateWad(名單outputList,列表inputList,布爾標誌){ ... }

而你需要做的呢?假設每個列表中的對象可以通過它們的equals方法進行比較。

public List<T> CalculateWad<T, TH>(List<T> outputList, List<TH> inputList, bool flag) { 

       // cast list to be regular object lists 
       List out = (List) outputList; 
       List in = (List) inputList; 

       for(Object object : in){ 
        out.remove(object); // this looks for an object that matches using contract.equals(object)   
       } 
} 

標誌變量是什麼?

+0

這是爲了別的。 – 2012-08-13 12:48:51

3

爲了訪問合同屬性,泛型T和TH必須實現與合同屬性的接口。

文檔:where (generic type constraint) (C# Reference)

interface IContractable { string Contract { get; } } 

然後你包含CalculateWad方法類必須定義如下:

class MyClass<T, TH> 
    where T : IContractable 
    where TH : IContractable 
{ 
    public List<T> CalculateWad(List<T> outputList, List<TH> inputList, bool flag) 
    { 
     return outputList 
        .Where(o => 
         inputList.Select(i => i.Contract).Contains(o.Contract) == false) 
        .ToList(); 
    } 
} 
+0

+1猜你比我快。我將輸入列表中的合約明確地複製到一個集合中。這可以節省一點運行成本,不是嗎? – 2012-08-13 12:57:21

+1

我不確定,我不是Linq嚮導,但我認爲Linq必須將其作爲優化來完成。最好問問Jon Skeet :) – 2012-08-13 13:00:39

+0

兩個列表中的契約屬性都是字符串類型。顯然,這是我想要的,但它不起作用。 – 2012-08-13 13:51:16

2

這應工作,通過增加共同IHasContract接口,這兩個TTH必須執行:

class Program 
{ 
    static void Main(string[] args) 
    { 
    } 

    private IList<T> CalculateWad<T, TH>(IList<T> output, 
     IList<TH> input, bool flag) 
     where T : IHasContract 
     where TH : IHasContract 
    { 
     var contracts = new HashSet<string >(input.Select(i => i.Contract)); 

     var qry = from o in output 
        where !contracts.Contains(o.Contract) 
        select o; 

     return qry.ToList(); 
    } 

    private sealed class Contract 
    { 

    } 

    private interface IHasContract 
    { 
     string Contract { get; } 
    } 

    private sealed class Foo : IHasContract 
    { 
     public string Contract { get; set; } 
    } 

    private sealed class Bar : IHasContract 
    { 
     public string Contract { get; set; } 
    } 
} 

請注意,不會修改output,您在文中提到。但是,它確實返回了該列表的新更改副本,這可能更像是方法簽名描述的內容。