Convert VB to C # using lambdas

I have some code that I am tasked with converting to C # from VB. My fragment seems that it cannot be converted from one to another, and if so, I just don’t know how to do it, and I'm a little upset.

Here is some background:

OrderForm- class abstractinherited Invoice(as well PurchaseOrder). The following VB snippet works correctly:

Dim Invs As List(Of OrderForm) = GetForms(theOrder.OrderID)
....
Dim inv As Invoice = Invs.Find(
    Function(someInv As Invoice) thePO.SubPONumber = someInv.SubInvoiceNumber)

In C #, I came up with the best conversion:

List<OrderForm> Invs = GetForms(theOrder.OrderID);
....
Invoice inv = Invs.Find(
    (Invoice someInv) => thePO.SubPONumber == someInv.SubInvoiceNumber);

However, when I do this, I get the following error:

Cannot convert lambda expression for delegation of type "System.Predicate" because parameter types do not match delegate parameter types

Is there a way to fix this without rebuilding my entire codebase?

+3
source share
5

, OrderForm Invoice. , , Find. ( VB, # , .)

Invoice inv = Invs.Find(someInv => thePO.SubPONumber == someInv.SubInvoiceNumber); 

, , .

Invoice inv = (Invoice)Invs.Find(someInv => 
                   thePO.SubPONumber == ((Invoice)someInv).SubInvoiceNumber);  

LINQ, Find List<>

Invoice inv = Invs.OfType<Invoice>().FirstOrDefault<Invoice>(someInv => someInv.SubInvoiceNumber == thePO.SubPONumber);
+2

, VB #, . , #. VB

Strict On - 'System.Predicate(Of )

, . #, , , VB:

Dim inv As Invoice = DirectCast(Invs.Find(Function(someInv As OrderForm) SubPONumber = DirectCast(thePO.SubPONumber, Invoice).SubInvoiceNumber), Invoice)

UPDATE

# @Anthony Pegram:

Invoice inv = (Invoice)Invs.Find(someInv => thePO.SubPONumber == ((Invoice)someInv).SubInvoiceNumber);

, , . GetForms() OrderForms, , Invoices. , , . , GetForms() Invoices .

+5

, Find Predicate<OrderForm>, Predicate<Invoice>. , . , VB.NET.

thePO?

, Find OrderForm, Invoice.

- :

OrderForm orderForm = Invs.Find(o => o.SomeOrderFormProperty == someValue);

-, - :

Invoice invoice = Invs.OfType<Invoice>()
                      .SingleOrDefault(x => x.SomeInvoiceProperty == someValue);

if(invoice != null) {
    // do something
}

, Invoice s, List<OrderForm> List<Invoice>?

+3
source

Edit:

You don’t really need to create a new list.

List<OrderForm> Invs = new List<OrderForm> { new Invoice(1), new Invoice(2) };  
List<Invoice> invoices = Invs.OfType<Invoice>().Where(invoice => invoice.val == 1).ToList();
+1
source

I assume that you need to direct OrderFormto Invoice:

Invoice inv = (Invoice)Invs.Find(
    someInv => thePO.SubPONumber == ((Invoice)someInv).SubInvoiceNumber); 
0
source

Source: https://habr.com/ru/post/1783779/


All Articles