How do I copy two similar lists? - c#

I have two lists. There are only one field difference. How to fill the lists with each other.
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
I fill out lists from files.
then,I need to fill out the list two from list one,There are many fields And I do not want to use the foreach loop.
It should be remembered that my previous class was already built and serialized and stored in a file. And now I need to transfer the previous information to the second class structure.
I do not want to use this loop!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}

Is this what you want?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
It copies everything from list 1 to list2.

No need to waste your time and money, AutoMapper can do it for you with only 2 lines of code:
using AutoMapper;
namespace ConsoleApp39
{
class Program
{
static void Main (string[] args)
{
// fill list1 with data
var list1 = new List1
{
Field1 = "test",
Field2 = 5,
Field3 = false,
};
// 1) configure auto mapper
Mapper.Initialize (cfg => cfg.CreateMap<List1, List2> ());
// 2) create list2 and fill with data from list1
List2 list2 = Mapper.Map<List2> (list1);
// fill extra fields
list2.Field4 = new byte[] { 1, 2, 3 };
}
}
public class List1
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
public class List2
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
public byte[] Field4 { get; set; } // extra field
}
}

Do Lst1 can inheritance from Lst2?
Something like this,
the two lists:
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public int filed2 { get; set; }
public bool filed100 { get; set; }
}
[Serializable()]
public class Lst2 : Lst1
{
public string filed101 { get; set; }
}
and one print extension
public static class CExtensions
{
public static string PropertyList(this Lst1 obj)
{
var props = obj.GetType().GetProperties();
var sb = new StringBuilder();
foreach (var p in props)
{
sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
}
return sb.ToString();
}
}
then using it:
class Program
{
static void Main(string[] args)
{
const int I = 15;
try
{
//init first list
List<Lst1> Lst1_ = new List<Lst1>();
Init(Lst1_);
//print it
Console.WriteLine("Lst1_");
Console.WriteLine(new string('-', I));
Lst1_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
//init second list
List<Lst1> Lst2_ = Lst1_.Cast<Lst1>().ToList(); //equivalent of two next lines
//List<Lst1> Lst2_ = new List<Lst2>().ConvertAll(x => (Lst1)x);
//Lst2_.AddRange(Lst1_);
//add one more
Lst2_.Add(new Lst2
{
filed1 = "101",
filed2 = 202,
filed100 = true,
filed101 = "10100"
});
//and print
Console.WriteLine("Lst2_");
Console.WriteLine(new string('-', I));
Lst2_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
private static void Init(List<Lst1> lst_)
{
for (int i = 1; i <= 3; i++)
{
lst_.Add(new Lst1
{
filed1 = i.ToString(),
filed2 = 2 * i,
filed100 = i % 2 == 0
});
}
}
}
enjoy =)

Related

How to use Linq add list data to list sub class?

i want add list data (from class) to sub class list for sent JSON FORMAT to other api.
Class
public class InPaymentDetailResponse
{
public List<InPaymentDetail> Data { get; set; }
}
public class InPaymentDetail
{
public string runningno { get; set; }
public decimal totalpremium { get; set; }
}
public class InformationRequest
{
.....
.....
public List<CreateDetailRequest> _detailData { get; set; }
public ExPaymentRequest _payment { get; set; }
}
public class ExPaymentRequest
{
.....
.....
public ExCashtransaction _cash { get; set; }
}
public class ExCashtransaction
{
public string createby { get; set; }
public DateTime createdate { get; set; }
public List<ExCashtransactionDetailsRequest> details { get; set; }
}
public class ExCashtransactionDetailsRequest
{
public string runningno { get; set; }
public decimal amount { get; set; }
}
Code C#
private async Task<.....> CreateInfo(InformationRequest r)
{
InPaymentDetailResponse resPaymentDetail = new InPaymentDetailResponse();
resPaymentDetail.Data = new List<InPaymentDetail>();
foreach (var item in r._detailData)
{
.....
..... //Process Data
.....
var resPaymentDetailData = new InPaymentDetail
{
//Add List Data To New Object
runningno = item.runningno,
totalpremium = item.totalpremium
};
resPaymentDetail.Data.Add(resPaymentDetailData);
}
HttpResponseMessage response = new HttpResponseMessage();
foreach (var res in resPaymentDetail.Data.ToList())
{
//i want add
//req._payment._cash.details.runningno = res.runningno //Ex. 10
//req._payment._cash.details.amount = res.amount //Ex. 99.9
//next loop
//req._payment._cash.details.runningno = res.runningno //Ex. 20
//req._payment._cash.details.amount = res.amount //Ex. 23.2
}
//sent to other api
response = await client.PostAsJsonAsync("", req._payment._cash);
.....
.....
}
i want result code when add list data to req._payment._cash:
(because to use it next process)
"createby": "system",
"createdate": 26/09/2018",
"details": [
{
"runningno": "10", //before add data to list is null
"amount": 99.9 //before add data to list is null
},
{
"runningno": "20", //before add data to list is null
"amount": 23.2 //before add data to list is null
}
]
Help me please. Thanks in advance.
List<ExCashtransactionDetailsRequest> detailsObj = new List<ExCashtransactionDetailsRequest>();
foreach (var res in resPaymentDetail.Data.ToList())
{
detailsObj.Add(new ExCashtransactionDetailsRequest(){ runningno =res.runningno, amount = res.amount });
}
and finally, add details object to your property
req._payment._cash.details = detailsObj;

Various ways to combine two different result sets and do the iteration and sum

Here I have a class List1 and classes List2,ListViewModel for combining two datasets, and I have two different result sets, each list having four values and I need to combine them as a single resultset with 4 rows and need to do the iteration and summation by using the result values in upcoming resultset.
I have tried Both Ways :
Method 1:
var list1 = List1.GetList1();
var list2 = List2.GetList12();
List<ListViewModel> listViewmodelCollection = new List<ListViewModel>();
ListViewModel listViewmodelInstance = new ListViewModel();
foreach (var _list1 in list1)
{
listViewmodelInstance.LocationValues1 = _list1.LocationValues1;
listViewmodelInstance.LocationValues2 = _list1.LocationValues2;
foreach (var _list2 in list2)
{
listViewmodelInstance.LocationValues5 = _list2.LocationValues5;
listViewmodelInstance.LocationValues4 = _list2.LocationValues4;
listViewmodelInstance.RA = _list1.LocationValues1 + _list2.LocationValues4;
listViewmodelCollection.Add(listViewmodelInstance);
}
}
Method2:
List<ListViewModel> listViewmodelCollection = new List<ListViewModel>();
ListViewModel listViewmodelInstance = new ListViewModel();
var x = (from listobj in m.list
from n in m.list2
select new list4
{
LocationValues1 = listobj.LocationValues1,
LocationValues2 = n.LocationValues4,
LocationValues4 = listobj.LocationValues1 + n.LocationValues4
});
-- complete --
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace simple
{
class Program
{
public class List2
{
public string ContinentName { get; set; }
public decimal LocationValues4 { get; set; }
public decimal LocationValues5 { get; set; }
public Nullable<System.DateTimeOffset> CreatedDate { get; set; }
public static List<List2> GetList12()
{
var list2 = new List<List2>
{
new List2{ ContinentName="Asia",LocationValues4=399.23M,LocationValues5=22.90M },
new List2 { ContinentName ="Africa",LocationValues4=199.23M,LocationValues5=22.90M },
new List2 { ContinentName ="Australia",LocationValues4=199.23M,LocationValues5=22.90M },
new List2 { ContinentName ="Pakistan",LocationValues4=199.23M,LocationValues5=22.90M },
};
return list2;
}
}
public class List1
{
public string LocationName { get; set; }
public decimal LocationValues1 { get; set; }
public decimal LocationValues2 { get; set; }
public Nullable<System.DateTimeOffset> CreatedDate { get; set; }
public static List<List1> GetList1()
{
var list1 = new List<List1>
{
new List1 {LocationName="Africa",LocationValues1=199.23M,LocationValues2=22.90M },
new List1 {LocationName="Africa",LocationValues1=299.23M,LocationValues2=24.90M },
new List1 {LocationName="Africa",LocationValues1=399.23M,LocationValues2=25.90M },
new List1 {LocationName="Africa",LocationValues1=499.23M,LocationValues2=26.90M },
};
return list1;
}
}
public class ListViewModel
{
public string LocationName { get; set; }
public decimal LocationValues1 { get; set; }
public decimal LocationValues2 { get; set; }
public Nullable<System.DateTimeOffset> LocationCreatedDate { get; set; }
public decimal RA { get; set; }
public string ContinentName { get; set; }
public decimal LocationValues4 { get; set; }
public decimal LocationValues5 { get; set; }
public Nullable<System.DateTimeOffset> ContinentCreatedDate { get; set; }
}
static void Main(string[] args)
{
var list1 = List1.GetList1();
var list2 = List2.GetList12();
List<ListViewModel> listViewmodelCollection = new List<ListViewModel>();
ListViewModel listViewmodelInstance = new ListViewModel();
foreach (var _list1 in list1)
{
listViewmodelInstance.LocationValues1 = _list1.LocationValues1;
listViewmodelInstance.LocationValues2 = _list1.LocationValues2;
foreach (var _list2 in list2)
{
listViewmodelInstance.LocationValues5 = _list2.LocationValues5;
listViewmodelInstance.LocationValues4 = _list2.LocationValues4;
listViewmodelInstance.RA = _list1.LocationValues1 + _list2.LocationValues4;
listViewmodelCollection.Add(listViewmodelInstance);
}
}
}
Expected Output:
4 Rows
LocationName="Africa",LocationValues1=199.23M,LocationValues2=22.90M,ContinentName="Asia",LocationValues4=399.23M,LocationValues5=22.90M, RA=598.46
LocationName="Africa",LocationValues1=299.23M,LocationValues2=24.90M ,ContinentName ="Africa",LocationValues4=199.23M,LocationValues5=22.90M,RA=465.46
LocationName="Africa",LocationValues1=399.23M,LocationValues2=25.90M ContinentName ="Australia",LocationValues4=199.23M,LocationValues5=22.90M,RA=598.46
LocationName="Africa",LocationValues1=499.23M,LocationValues2=26.90M , ContinentName ="Pakistan",LocationValues4=199.23M,LocationValues5=22.90M.RA=698.46
But current output:
So, this seems messy at best. I'm not sure what your situation is but I would be very nervous about coding to merge 2 different data lists and expecting them to always be equal lengths etc..
I would strongly recommend that you add an interface to both lists so you could at least cast them to a base object and work with them that way instead.
That said I would try to select out the view model attributes via linq from the first set, then iterate through to add the data from the 2nd set and do the computations then.
Example:
var list1 = List1.GetList1();
var list2 = List2.GetList12();
List<ListViewModel> listViewmodelCollection = new List<ListViewModel>();
ListViewModel listViewmodelInstance = new ListViewModel();
listViewmodelCollection.AddRange(list1.Select(l => new ListViewModel()
{
LocationName = l.LocationName,
LocationCreatedDate = l.CreatedDate,
LocationValues1 = l.LocationValues1,
LocationValues2 = l.LocationValues2
}));
for (int i = 0; i < (listViewmodelCollection.Count - 1); i++)
{
var itm2 = list2.ElementAt(i);
if (itm2 != null)
{
listViewmodelCollection[i].ContinentName = itm2.ContinentName;
listViewmodelCollection[i].ContinentCreatedDate = itm2.CreatedDate;
listViewmodelCollection[i].LocationValues4 = itm2.LocationValues4;
listViewmodelCollection[i].LocationValues5 = itm2.LocationValues5;
listViewmodelCollection[i].RA = listViewmodelCollection[i].LocationValues1 + itm2.LocationValues4;
}
}
Given your classes this should get you to the output you wanted, at least for this narrow example.
You can use LINQ to combine the two Lists using the Zip extension method:
var listViewmodelCollection = list1.Zip(list2, (l1, l2) => new ListViewModel {
LocationName = l1.LocationName,
LocationValues1 = l1.LocationValues1,
LocationValues2 = l1.LocationValues2,
ContinentName = l2.ContinentName,
LocationValues4 = l2.LocationValues4,
LocationValues5 = l2.LocationValues5,
RA = l1.LocationValues1+l2.LocationValues4
}).ToList();

Pass list from model class to DbInitliazer

I'm new to C#. I'm working on a web app project. I want to know how to initialize the list in my DbInitializer class. For example, this is the Model:
using System;
using System.Collections.Generic;
namespace Manager.Model
{
public class Vendor
{
public int VendorID { get; set; }
public string CardName { get; set; }
public string WebsiteLink { get; set; }
public DateTime PartnerSince { get; set; }
public List<Rep> Reps { get; set; }
public string SupportNo { get; set; }
public string SupportEmail { get; set; }
public string Rebate { get; set; }
public string Spiff { get; set; }
public string Quote { get; set; }
}
public class Rep
{
public string RepName { get; set; }
public string RepPosition { get; set; }
public string RepNo { get; set; }
public string RepEmail { get; set; }
}
}
How would I pass this list in the Initialize method?
public static void Initialize(ManagementContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Vendors.Any())
{
return; // DB has been seeded
}
var vendors = new Vendor[]
{
new Vendor{CardName="Vendor1", WebsiteLink="www.vendor1.com", PartnerSince=DateTime.Parse("10-10-2012"), SupportNo="521-586-8956", SupportEmail="nikki#vendor1.com"},
};
foreach (Vendor v in vendors)
{
context.Vendors.Add(v);
}
context.SaveChanges();
If you'd like to do everything inline:
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = new List<Rep>()
{
new Rep() // first rep
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
}
// , new Rep(){...} // second rep, etc...
}
}
// , new Vendor(){....} // second vendor, etc...
};
Or simply prepare the Reps first:
List<Rep> Reps1 = new List<Rep>(); // Reps 1 for Vendor 1
Reps1.Add(new Rep()
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
});
// you may add more rep
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = Reps1
}
// , new Vendor(){....} // second vendor, etc...
};
For question if you change into string[] RepNames,
string[] RepNames1 = new string[]
{
"name1",
"name2" // , etc....
}
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
RepNames = RepNames1
}
// , new Vendor(){....} // second vendor, etc...
};

return multiple reader.cast<>

All I want to do is return multiple reader.cast<> so that i can use 2 sqlcommands.
var first =reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).ToList();
reader.NextResult();
var second=reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names2 = x.GetString(0),
Values2 = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble2 = x.GetDouble(1)
}).ToList();
All I want to do is return var first and var second. Please help :(
I'm using this Location.cs for parameters:
namespace MVCRealtime
{
public class LocationInfo
{
public string Names { get; set; }
public string Values { get; set; }
public double ValuesDouble { get; set; }
public string Names2 { get; set; }
public string Values2 { get; set; }
public double ValuesDouble2 { get; set; }
}
}
public static class ReaderHelper
{
public static IEnumerable<TElem> GetData<TElem>(this IDataReader reader, Func<IDataRecord, TElem> buildObjectDelegat)
{
while (reader.Read())
{
yield return buildObjectDelegat(reader);
}
}
}
// ...
var result = reader.GetData(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).Take(2);
So you get 1st var in 1st element of the result and 2nd var in 2nd element.

Adding Fulfillment to Shopify orders

This is my code in adding Fulfillment to Shopify orders but the converted json is not as expected.
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = orderSent.TrackingNo;
List<LineItems> items = new List<LineItems>();
foreach (var item in orderSent.OrderLines)
{
LineItems line = new LineItems();
line.id = item.ProductName;
items.Add(line);
}
var json = JsonConvert.SerializeObject(product);
json = "{ \"fulfillment\": " + json + "}";
var json1 = JsonConvert.SerializeObject(items);
json = json + "{ \"line_items\": " + json1 + "}";
And this the converted json from this code:
{ "fulfillment": {
"id":0,
"status":"success",
"tracking_number":"xxxx12222",
}}{
"line_items": [
{
"id":"1234566645"
}
]
}
How can I turned like this:
{
"fulfillment": {
"tracking_number": null,
"line_items": [
{
"id": 466157049,
"quantity": 1
}
]
}
}
Model:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Fullfillment
{
[JsonProperty(PropertyName = "id")]
public long id { get; set; }
[JsonProperty(PropertyName = "status")]
public string status { get; set; }
[JsonProperty(PropertyName = "tracking_number")]
public string tracking_number { get; set; }
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LineItems
{
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
}
These are the models for Fulfillment and Line Items.
Thank you in advance for giving advices and help.
This works for me:
var json = JsonConvert.SerializeObject(new
{
fullfillment = new
{
product.tracking_number,
line_items = items.Select(x => new
{
x.id,
quantity = 1
})
}
});
That gives me:
{
"fullfillment" : {
"tracking_number" : "xxxx12222",
"line_items" : [{
"id" : "1234566645",
"quantity" : 1
}
]
}
}
I started with this code to build up the JSON above:
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = "xxxx12222";
List<LineItems> items = new List<LineItems>();
LineItems line = new LineItems();
line.id = "1234566645";
items.Add(line);
Obviously you need to fill in your specific data.
Change your classes like below.
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}
This will give you this json.
{
"fulfillment": {
"tracking_number": "xxxx12222",
"line_items": [
{
"id": "1234566645",
"quantity": 1
}
]
}
}
Try the following
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}

Categories

Resources