Multiple Array Insertion in C# using Foreach statement - c#

private void Updated_ModRecFGA()
{
try
{
DRFGAModifiedRecord TABLE = new DRFGAModifiedRecord();
foreach (ArrayFunc Row in ArrayFunc.QueryResult)
{
foreach (ArrayFunc Row2 in ArrayFunc.QueryResult1)
{
TABLE.RecordDocID = Row.FGACol1;
TABLE.DRNo = Row.FGACol2;
TABLE.DDNum = Row.FGACol3;
TABLE.LineNumber = Row.FGACol4;
TABLE.Itemnmbr = Row2.updItemCode;
TABLE.Itemdesc = Row2.updItemDesc;
TABLE.Pallet = Row2.updPallets;
TABLE.BagsNo = Row2.updBagsNo;
TABLE.TotalLoaded = Row2.updTotalKgs;
TABLE.PostStat = Row2.updPostStat;
TABLE.ProdCode = Row2.updProdcode;
TABLE.VariantCode = Row2.updVariantCode;
TABLE.DateModify = DateTime.Now.ToShortDateString();
TABLE.TimeModify = DateTime.Now.ToShortTimeString();
TABLE.UserModify = "Mik";//GlobalvarClass.LogUser;
TABLE.ReasonModify = GlobalvarClass.GetModReasOnDR;
TABLE.FileType = "New";
saveREC(TABLE);
gfunc.MsgBox("Saved", 1);
}
}
ArrayFunc.QueryResult.Clear();
ArrayFunc.QueryResult1.Clear();
GlobalvarClass.GetModReasOnDR = string.Empty;
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
}
Is there another proper way to use this kind of code something like this to avoid duplicate? I know it duplicate because of two foreach statement

Just combine the two using linq. Remember to include using System.Linq; in your using clause.
var results = ArrayFunc.QueryResult.SelectMany(l1 => ArrayFunc.QueryResult1, (l1, l2) =>
new DRFGAModifiedRecord
{
RecordDocID = l1.FGACol1,
DRNo = l1.FGACol2,
DDNum = l1.FGACol3,
LineNumber = l1.FGACol4,
Itemnmbr = l2.updItemCode,
Itemdesc = l2.updItemDesc,
Pallet = l2.updPallets,
BagsNo = l2.updBagsNo,
TotalLoaded = l2.updTotalKgs,
PostStat = l2.updPostStat,
ProdCode = l2.updProdcode,
VariantCode = l2.updVariantCode,
DateModify = DateTime.Now.ToShortDateString(),
TimeModify = DateTime.Now.ToShortTimeString(),
UserModify = "Mik",//GlobalvarClass.LogUser
ReasonModify = GlobalvarClass.GetModReasOnDR,
FileType = "New"
}).ToList();
foreach (row in results)
{
saveREC(row);
gfunc.MsgBox("Saved", 1);
}
Alternatively you can do it with a query expression:
var result = (from l1 in ArrayFunc.QueryResult
from l2 in ArrayFunc.QueryResult1
select new DRFGAModifiedRecord { RecordDocID = l1.FGACol1 ... }).ToList();

Related

how to return an object in c#?

I'm filling data inside an object with c# but I don't know how to return this object.
I create an object named ArasOrder and fill in the data and I want to return the ArasOrder object.
how can I do this.
public class ArasDeneme
{
public static void aras()
{
var ArasService = new ArasTEST.Service();
var ArasGonderi = new ArasTEST.ShippingOrder();
var ArasOrder = new ArasTEST.Order();
var parametreler = ArasKargoTEST.ParametreGet();
var newentegrationcode = "";
foreach (var item in parametreler)
{
var encode = entegrationcode();
var YeniGelenDesi = DesiHesabi(item.WebSiparisNo);
var yeniteminyeri = item.TeminYeri;
newentegrationcode = 123+ "" + encode;
ArasOrder.UserName = "";
ArasOrder.Password = "";
ArasOrder.ReceiverName = item.KargoAdSoyad;
ArasOrder.ReceiverPhone1 = item.KargoTelefon;
ArasOrder.ReceiverCityName = item.KargoIlAdi;
ArasOrder.ReceiverTownName = item.KargoIlceAdi;
ArasOrder.ReceiverAddress = item.KargoAdres;
ArasOrder.TradingWaybillNumber = item.WebSiparisNo;
ArasOrder.PieceCount = "1";
ArasOrder.IntegrationCode = newentegrationcode;
ArasOrder.PayorTypeCode = "1";
ArasOrder.IsWorldWide = "0";
ArasOrder.IsCod = "0";
ArasOrder.VolumetricWeight = YeniGelenDesi;
ArasOrder.SenderAccountAddressId = "1071";
ArasTEST.PieceDetail[] ArasPieceDetails = new ArasTEST.PieceDetail[1];
PieceDetail ArasPieceDetail1 = new PieceDetail();
ArasPieceDetail1.BarcodeNumber = newentegrationcode;
ArasPieceDetail1.VolumetricWeight = YeniGelenDesi;
ArasPieceDetail1.Weight = "1";
ArasPieceDetail1.Description = "";
ArasPieceDetails[0] = ArasPieceDetail1;
ArasOrder.PieceDetails = ArasPieceDetails;
var ArasOrderInfo = new ArasTEST.Order[1];
ArasOrderInfo[0] = ArasOrder;
var takipNoResult = ArasService.SetOrder("", "", "");
var ArasOrderResultInfo = takipNoResult[0];
var SonucKodu = takipNoResult[0].ResultCode;
var SonucMesaji = takipNoResult[0].ResultMessage;
var SonucInvoiceKey = takipNoResult[0].InvoiceKey;
}
}
}
You should define the return type and return the instance.
public static ArasTEST aras()
{
// insert code here...
return ArasOrder;
}
Change void to ArasDeneme return type.
Then call like:
var ad = ArasDeneme.aras();

add two group into one group in c#

I have two groups like below, theyh have different data. Based on both I need to create an xml file .
How can I write a for-loop for both groups and generate a single xml file?
var groups = checkFile.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("orderid"), Type = x.Field<string>("Type"), ProdName = x.Field<string>("ProdName"), Status = x.Field<string>("Status"), productno = x.Field<string>("productno"), uom = x.Field<string>("uom"), customer = x.Field<string>("customer"), remark = x.Field<string>("remark"), U_JobNumber = x.Field<string>("U_JobNumber"), U_SalesPerson = x.Field<string>("U_SalesPerson"), U_POnum = x.Field<string>("U_POnum"), U_JobType = x.Field<string>("U_JobType"), PlannedQty = x.Field<decimal>("PlannedQty"), OriginNum = x.Field<int?>("OriginNum"), orderdate = x.Field<DateTime>("orderdate"), duedate = x.Field<DateTime>("duedate"), DocTotal = x.Field<decimal>("DocTotal") });
var groups2 = checkFile2.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("DocNum") });
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings { Indent = true }))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
docSave.Save(System.IO.Path.Combine(#SystemSettings.ImportBankStatementPendingFolderPath, "DocNum -" + group.Key.DocNum + ".xml"));
count++;
}
Try following :
DataTable checkFile = new DataTable();
var groups = checkFile.AsEnumerable().GroupBy(x => new
{
DocNum = x.Field<int>("orderid"),
Type = x.Field<string>("Type"),
ProdName = x.Field<string>("ProdName"),
Status = x.Field<string>("Status"),
productno = x.Field<string>("productno"),
uom = x.Field<string>("uom"),
customer = x.Field<string>("customer"),
remark = x.Field<string>("remark"),
U_JobNumber = x.Field<string>("U_JobNumber"),
U_SalesPerson = x.Field<string>("U_SalesPerson"),
U_POnum = x.Field<string>("U_POnum"),
U_JobType = x.Field<string>("U_JobType"),
PlannedQty = x.Field<decimal>("PlannedQty"),
OriginNum = x.Field<int?>("OriginNum"),
orderdate = x.Field<DateTime>("orderdate"),
duedate = x.Field<DateTime>("duedate"),
DocTotal = x.Field<decimal>("DocTotal")
});
DataTable checkFile2 = new DataTable();
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
List<DataRow> groups2 = checkFile2.AsEnumerable().Where(x => group.Key.DocNum == x.Field<int>("DocNum")).ToList();
}

how to get all the items of list c#

In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}

How to apply multiple optional filters in a LINQ query

I have a page where user can select any number of search filters to apply search
When user clicks on search, these parameters are passed to my GetIndicatorData method to perform the query. However, it doesn't seem to work for me.
Here is my code
public static List<tblindicators_data_custom> GetIndicatorsData(string status, int service_id, int operator_id, string year, string frequency)
{
var date = Convert.ToDateTime(year + "-01-01");
int[] numbers = status.Split(',').Select(n => int.Parse(n)).ToArray();
var ict = new ICT_indicatorsEntities();
var result = from ind in ict.tblindicators_data
join ser in ict.tblservices on ind.service_id equals ser.Id
join oper in ict.tbloperators on ind.operator_id equals oper.Id
where numbers.Contains(ind.status) && (ind.date_added.Year == date.Year)
select new
{
ind.Id,
ind.service_id,
ind.survey_id,
ind.operator_id,
ind.type,
ind.date_added,
ind.quater_start,
ind.quater_end,
ind.status,
ind.month,
service = ser.name,
operator_name = oper.name
};
List<tblindicators_data_custom> data = new List<tblindicators_data_custom>();
foreach (var item in result)
{
tblindicators_data_custom row = new tblindicators_data_custom();
row.Id = item.Id;
row.survey_id = item.survey_id;
row.service_id = item.service_id;
row.service_name = item.service;
row.operator_id = item.operator_id;
row.operator_name = item.operator_name;
row.date_added = item.date_added;
row.quater_start = item.quater_start;
row.type = item.type;
row.quater_end = item.quater_end;
row.month = item.month == null? DateTime.Now:item.month;
row.status = item.status;
data.Add(row);
}
return data;
}

Entity Framework 5 will not allow .SaveChanges

I've upgraded to Entity Framework 5 and the .SaveChanges is no longer available.
How do we save our changes?
When ever I do a db.SaveChanges(); it errors because .SaveChanges is not there.
static bool Insert(Elevation elevation, out Elevation elevationOUT)
{
using (var db = new StorefrontSystemEntities())
{
//erik#afbs.net : DA91DC34-FA29-4ABD-BCC0-D04408310E3E
//projectID = 12
elevationOUT = null;
var projs = from p in db.Projects
where p.ID == elevation.ProjectID
select p;
//
var proj = projs.SingleOrDefault();
if (proj == null) { return false; }
//Elevation
var elev = new Elevation
{
ID = proj.ID,
Name = elevation.Name,
Note = elevation.Note,
ComponentID = elevation.CompID,
VerCutHD = elevation.VerCutHD,
VerCutSill = elevation.VerCutSill,
Created = DateTime.Now
};
proj.Elevations.Add(elev);
//Bays
foreach (var bay in elevation.Bays)
{
var b = new Bay
{
Position = bay.Position,
IsBulkhead = bay.IsBulkhead,
Note = bay.Note,
Size = GetClientSize(bay.Size),
IsFixed = bay.IsFixed,
Finish = GetClientFinish(bay.Finish),
Siteline = GetClientSiteline(bay.Siteline, elev.ComponentID),
VerCutHD = elevation.VerCutHD,
VerCutSill = elevation.VerCutSill
//
};
elev.Bays.Add(b);
};
db.SaveChanges();
elevationOUT = elev;
elevationOUT.IsGeneric = proj.GenericCatalogID > 0;
}
return true;
}

Categories