mih*_*hai 46 c# linq casting list .net-3.5
我有2个类,它们有一些相同的属性.我从第一类库存到列表属性,然后,我想获取一些所需的属性并将它们放入第二类类型的列表中.我已经通过C#制作了强制转换序列并运行正常,但我必须使用LINQ.我试图做一些事但没有好结果.请给我一些建议.
第一类:
public class ServiceInfo {
private long _id;
public long ID {
get { return this._id; }
set { _id = value; }
}
private string _name;
public string Name {
get { return this._name; }
set { _name = value; }
}
private long _qty;
public long Quantity {
get { return this._qty; }
set { _qty = value; }
}
private double _amount;
public double Amount {
get { return this._amount; }
set { _amount = value; }
}
private string _currency;
public string Currency {
get { return this._currency; }
set { _currency = value; }
}
private DateTime? _date;
public DateTime? Date {
get { return this._date; }
set { _date = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
第二类:
class InvoiceWithEntryInfo {
private string currencyField;
private long IdField;
public long IdIWEI {
get { return this.IdField; }
set { IdIWEI = value; }
}
private string nameField;
public string NameIWEI {
get { return this.nameField; }
set { NameIWEI = value; }
}
private long qtyField;
public long QuantityIWEI {
get { return this.qtyField; }
set { QuantityIWEI = value; }
}
private double amountField;
public double AmountIWEI {
get { return this.amountField; }
set { AmountIWEI = value; }
}
private DateTime dateField;
public DateTime? DateIWEI {
get { return this.dateField; }
set { DateIWEI = value; }
}
public string OwnerIWEI {
get; set;
}
}
Run Code Online (Sandbox Code Playgroud)
C#样本运行正常:...
var sil = new List<ServiceInfo>();
var iweil = new List<InvoiceWithEntryInfo>();
Run Code Online (Sandbox Code Playgroud)
...
if (sil != null)
{
foreach (ServiceInfo item in sil)
{
iweil.Add(new InvoiceWithEntryInfo
{
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date
});
}
Run Code Online (Sandbox Code Playgroud)
LINQ样本没有运行OK:
iweilCOPY = sil.ConvertAll<InvoiceWithEntryInfo>(a => (InvoiceWithEntryInfo)a);
iweilCOPY = sil.FindAll(a => (sil is InvoiceWithEntryInfo)).ConvertAll<InvoiceWithEntryInfo>(a => (InvoiceWithEntryInfo)a);
Run Code Online (Sandbox Code Playgroud)
vc *_* 74 77
var iweilCopy = sil.Select(item => new InvoiceWithEntryInfo()
{
IdWEI = item.Id,
NameWEI = item.Name,
....
}).ToList();
Run Code Online (Sandbox Code Playgroud)
Bob*_*ale 12
var iweil = sil.Select(item=> new InvoiceWithEntryInfo {
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date}).ToList();
Run Code Online (Sandbox Code Playgroud)
Ric*_*ard 10
您需要一个函数将T
实例转换为U
实例:
ResultType ConvertMethod(StartType input)
Run Code Online (Sandbox Code Playgroud)
你需要写这个.然后
outputList = inputList.Select(ConvertMethod).ToList();
Run Code Online (Sandbox Code Playgroud)
将它应用于整个输入集合.转换函数可以是内联写入的lambda,但不需要(如果函数具有正确的签名,ConvertMethod
那么编译器将正确转换它以传递给它Select
).
只需使用选择:
if(sil != null)
{
var iweil = sil.Select(item=>new InvoiceWithEntryInfo()
{
IdIWEI = item.ID,
AmountIWEI = item.Amount,
DateIWEI = item.Date
}).ToList();
}
Run Code Online (Sandbox Code Playgroud)