我有一個通用列表可以包含不同的類對象。這些類具有相同的具有Id屬性的基類。搜索通用列表<T>爲Id屬性
我願做此ID在列表中搜索和提取第一occourence,像這樣
T result = myGenericList.Where(i => i.Id == id).FirstOrDefault()
但是我不能去的屬性,我只得到儘可能爲:I = >我。
編輯: 我被要求提供myGenericList的代碼。這裏有雲:
public static IEnumerable<T> Initialize()
{
List<T> allCalls = new List<T>();
var phoneCalls = new PhoneCall[]
{
new PhoneCall{Id = 1, Date= DateTime.Now.AddDays(-1), DurationSec = 60, Phone = "", Region = new Country { From = "", To = ""}},
...
};
foreach (PhoneCall s in phoneCalls)
{
allCalls.Add(s as T);
}
var dataCalls = new DataCall[]
{
new DataCall{Id = 6, WebData = 5120, Phone = "", Region = new Country { From = "", To = ""}},
...
};
foreach (DataCall s in dataCalls)
{
allCalls.Add(s as T);
}
var smsCalls = new SmsCall[]
{
new SmsCall{Id = 6, SmsData = 512, Phone = "", Region = new Country { From = "", To = ""}},
...
};
foreach (SmsCall s in smsCalls)
{
allCalls.Add(s as T);
}
return allCalls;
關於第t是
public class Repository<T> : IRepository<T> where T : class
請出示的'myGenericList' –
什麼是T中的聲明?它是否正確轉換爲T型?你也可以請分享myGenericList? –
我猜T缺少T:BaseClass約束,它定義了Id屬性。也許這是一種擴展方法,它尚未將通用輸入類型限制爲任何東西。 –