In the code below, I would like the return from GetChainDetails to go where i have "I WANT MY LIST HERE" in GetChains method. Not sure how to accomplish or what other way to do this.
public static IEnumerable GetChains(int actGroupid, int dispid)
{
EEDBEntities db = new EEDBEntities();
var query = from c in db.Chains
where c.Activity_Basis.activity_group_id == actGroupid && c.Activity_Basis.discipline_id == dispid
select new
{
ChainID = c.ChainID,
ChainDesc = #"<span data-toggle=""tooltip"" title =""" + I WANT MY LIST HERE + #""">" + c.ChainID + "</span>"
};
return query.ToList();
}
public string GetChainDetails(string chainID)
{
string sStep = null;
var chainDetailList = from c in db.Chains_Detail
where c.chainID == chainID
orderby c.Order
select new
{
Order = c.Order,
Step = c.Step
};
foreach (var oItem in chainDetailList.ToList())
{
sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
}
return sStep;
}
Your method public string GetChainDetails(string chainID) is not static. Perhaps this is the reason you are getting error. Make it static and try and run the code.
public static string GetChainDetails(string chainID)
Also you can follow this approach :
class X
{
public int Property1;
public int Property2;
public string ChainID;
public string MyListToolTipText;
}
class Y
{
public string ChainID;
public string ChainDesc;
}
And your main code
class Program
{
static void Main()
{
var myResult = GetChains(1, 1);
foreach (var result in myResult)
{
result.ChainDesc = GetChainDetails(result.ChainID);
}
//you can use either foreach or linq
//var m = myResult.Select(result => result = new Y { ChainID = result.ChainID, ChainDesc = GetChainDetails(result.ChainDesc) });
}
public static IEnumerable<Y> GetChains(int actGroupid, int dispid)
{
var Chains = new List<X>();
var query = from c in Chains
where c.Property1 == actGroupid && c.Property2 == dispid
select new Y
{
ChainID = c.ChainID,
ChainDesc = #"<span data-toggle=""tooltip"" title =""" + c.MyListToolTipText + #""">" + c.ChainID + "</span>"
};
return query.ToList<Y>();
}
public static string GetChainDetails(string chainID)
{
string sStep = null;
var chainDetailList = from c in db.Chains_Detail
where c.chainID == chainID
orderby c.Order
select new
{
Order = c.Order,
Step = c.Step
};
foreach (var oItem in chainDetailList.ToList())
{
sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
}
return sStep;
}
}
Hence after calling GetChains, I am modifying each member property.
Related
I have a textbox where user types the string he needs to search. If the user enters only a single word string, then I am able to retrieve the correct data from database but if the user enters a multi-word string then my code fails.
I am using EntityFramework to get the data.
Here is my code to get the data using a single word string.
public ActionResult SearchResult(string search)
{
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
List<Mobiles> prod = new List<Mobiles>();
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
return View("~/Views/Product/Index.cshtml", prod);
}
I tried breaking the string into single word using split but could not get the correct data.
string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
string str = null;
string[] strArr = null;
int count = 0;
str = search;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
string i = strArr[count];
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
//MessageBox.Show(strArr[count]);
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
}
as I help you fix the problem - this is the final code
I Wrote an Example to Solve your Problem. Hope That You will Be Benefited From The Code.
First Create Mobile Class:
public class Mobile
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Next Create Extension method To Check If there is Value:
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (var needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
Finally Create Main Body Along with Test Data:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverFlow
{
static class Program
{
static void Main()
{
List<Mobile> mobiles = new List<Mobile>
{
new Mobile{Id = 1,Name = "samsung galaxy s3",Description = "model"},
new Mobile{Id = 2,Name = "nokia N67",Description = "nokia n96 time"},
new Mobile{Id = 3,Name = "iphone 5s",Description = "test"},
new Mobile{Id = 4,Name = "samsung galaxy packet",Description = "this time"},
new Mobile{Id = 5,Name = "iphone ipad",Description = "now"},
new Mobile{Id = 6,Name = "glx c5",Description = "time"},
};
string[] search = "galaxy time 5s".Split(' ');
var result = mobiles.Where(c => c.Name.ContainsAny(search) ||
c.Description.ContainsAny(search)).ToList();
foreach (var item in result)
{
Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Description);
}
Console.ReadKey();
}
I need to compare two lists of same type. Assume I have CurrentSC List(Current modified data by user) and PreviousSC List(Saved data from database) of below class.
public class SoftClose
{
private int AID = -1;
private bool _softCloseInd;
private bool _softCloseEditInd;
private string _softClosedBy;
private DateTime _softClosedDate;
private ReferenceEnums.ActionStatus _status = ReferenceEnums.ActionStatus.NO_CHANGE;
}
public static void TPostProcessAddRemoveSoftCloseStopPaymentPrefixes(IFPMServiceInternal fpmService, AgreementRevision revision)
{
List<SoftClose> psc = null;
List<SoftClose> csc = null;
string fanValue = revision.Agreement.FAN;
psc = fpmService.GetSoftCloseByFAN(fanValue);
if (psc != null)
{
//var currentprefixes = revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct();
//Create current SoftClose object using revision object
foreach (var prefix in revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct())
{
var newSF =
new SoftClose
{
Id = -1,
Status = ReferenceEnums.ActionStatus.NO_CHANGE,
AgreementRevId = revision.Id,
AgreementId = revision.Agreement.Id,
WorkflowStatus = revision.WorkflowStatus,
FAN = revision.Agreement.FAN,
PID = (int)revision.Agreement.PID,
Prefix = prefix
};
csc.Add(newSF);
}
//Now you have previous and current softcloses to compare prefixes...
psc.OrderBy(x => x.Prefix.Id);
csc.OrderBy(x => x.Prefix.Id);
for(int i = 0; i < csc.Count; i++)
{
}
}
}
Lets say I have changed D3 value in PreviousSC to D2 in CurrentSC. Now i need to delete D3 value from database(As D2 value already there in database i don't need to insert) and chnage _status to DELETE and I added D4 value in CurrentSC which is not there is PreviousSC. Now I need to add D4 value in database and assign _softCloseInd and _softCloseEditInd to Y and change _status to ADD.
How to achieve this in best way?
class Program
{
static void Main(string[] args)
{
List<SoftClose> psc = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID=19, Prefix = "D1"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=21, Prefix = "D3"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=22, Prefix = "D9"}
};
List<SoftClose> csc = new List<SoftClose>(){
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=19, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=21, Prefix = "D6"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=22, Prefix = "D4"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=23, Prefix = "D5"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=24, Prefix = "D3"}
};
List<SoftClose> esc = new List<SoftClose>();
Console.WriteLine("---------Previous List----------");
foreach (var item in psc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
Console.WriteLine("---------Current List----------");
foreach (var item in csc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
var addlist = csc.Where(c => psc.All(p => !p.Prefix.Equals(c.Prefix)));
foreach (var n in addlist)
{
var index = csc.FindIndex(p => p.Prefix.Equals(n.Prefix));
csc[index].Status = "ADD";
esc.Add(csc[index]);
}
var deletelist = psc.Where(p => p.Status.Equals("NO_CHANGE") && !csc.Exists(c => c.Prefix.Equals(p.Prefix)));
foreach (var n in deletelist)
{
var index = psc.FindIndex(c => c.Prefix.Equals(n.Prefix));
if (psc.FindIndex(c => c.Prefix.Equals(n.Prefix)) >= 0)
{
psc[index].Status = "REMOVE";
esc.Add(psc[index]);
}
}
Console.WriteLine("---------Effective List----------");
foreach (var item in esc)
{
Console.WriteLine($"Id:{item.ID}, Prefix:{item.Prefix}, Status:{item.Status}");
}
Console.ReadLine();
}
}
public class SoftClose
{
public int ID = -1;
public int AID = -1;
public int WFID = -1;
public string Prefix;
public DateTime SCDATE;
public string Status;
}
private XElement AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
}
return Author;
}
This is my method.. Form this method i need to return xelement. in this method i declared xelement in for loop. after for loop completed i need to return that xelement named as author. how to return that xelement?
If you declare the variable in the loop, you can use it only inside the loop. So in your case, you should declare it outside of the loop because you can't put the return statement inside for loop.
Edit:
private ArrayList AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
ArrayList authors = new ArrayList();
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
authors.Add(Author)
}
return authors;
}
If you want to create an XElement in each round, you can put them all in an ArrayList then return it.
I believe instead of returning XElement from function you should return List of XElement.
So you can write something like this:
private List<XElement> AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
var AuthorList = new List<XElement>();
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
AuthorList.Add(Author);
}
return AuthorList;
}
It will be better to return the list in the way above because here you will get a new XElement for every iteration of the loop.
I'm using System.Linq.Dynamic to make dinanmico where in my research. In the code below I try to filter by Funcao, but returns the error:
No property or field 'Funcao' exists in type 'ASO'
How do I filter by an alias of my Linq?
CODE
public static ResultadoListagemPadrao Grid(int iniciarNoRegistro, int qtdeRegistro, string orderna, string ordenaTipo, string filtro, int filtroID, UsuarioLogado usuarioLogado)
{
var where = "";
var id = 0;
if (filtroID > 0)
where += " FuncionarioID == " + filtroID.ToString();
else
{
if (int.TryParse(filtro, out id))
where += " ASOID == " + id.ToString();
if (filtro != null)
where += " Funcao.Contains(#0) ";
}
using (var db = new ERPContext())
{
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
resultado.TotalRegistrosVisualizados = db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro).Count();
resultado.Dados =
(from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro)
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
}
}
Issue is this line db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro)
Your class ASO doesn't have a property Funcao.
Try remove the Where on that line. Try this...
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
var query = (from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro);
resultado.TotalRegistrosVisualizados = query.Count();
resultado.Dados = query
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
Please in future translate your code.
How loop sub classes properties from the main class?
public class GroupA
{
public string FullName = "", BirthDay = "";
}
public class GroupB
{
public string Email = "";
}
public class GroupC
{
public string Phone;
}
public class MainGroup
{
public GroupA GroupA;
public GroupB GroupB;
public GroupC GroupC;
}
protected void Page_Load(object sender, EventArgs e)
{
GroupA NewGroupA = new GroupA();
NewGroupA.FullName="TEST MASTER";
NewGroupA.BirthDay="02/20/1984";
GroupB NewGroupB = new GroupB();
NewGroupB.Email="noreply#test.com";
GroupC NewGroupC=new GroupC();
NewGroupC.Phone="555 123 4567";
//Assign new class instances to the main class
MainGroup NewMainGroup= new MainGroup();
NewMainGroup.GroupA=NewGroupA;
NewMainGroup.GroupB=NewGroupB;
NewMainGroup.GroupC=NewGroupC;
//Loop through the main class
foreach (var Group in typeof(MainGroup).GetFields())
{
Response.Write("<BR>MainGroupName= " + Group.Name + " Value= " + Group.GetValue(NewMainGroup).ToString());
//PROBLEM IS HERE. Can't loop through the subclass We need to display the GroupA, GroupB, GroupC below.
foreach (var SubGroup in Group)
{
Response.Write("<BR>");
}
}
}
If I understand your question right, I think this code is your answer:
foreach (var group in NewMainGroup.GetType().GetFields())
{
var groupInstance = group.GetValue(NewMainGroup);
foreach (var subGroup in groupInstance.GetType().GetFields())
{
Response.Write("<br />" + subGroup.Name + " = " + subGroup.GetValue(groupInstance));
}
}
What you should to is store a reference to the group-variable (not just the type). So, if you take your code and do something like this:
foreach (var GroupType in typeof(MainGroup).GetFields())
{
object Group = GroupType.GetValue(NewMainGroup);
Response.Write("<BR>MainGroupName= " + GroupType.Name + " Value= " + Group.ToString());
foreach(var SubGroupType in Group.GetType().GetFields()) {
object SubGroup = SubGroupType.GetValue(Group);
Response.Write("<BR>SubGroupName= " + SubGroupType.Name + " Value= " + SubGroup.ToString());
}
}
Haven't tested it, but I think that should about work. At least get you started.
Oh, and by the way, I think I have a better method for you, try this one:
public Dictionary<string, object> GetObjectFields(object obj) {
var dict = new Dictionary<string, object>();
var t = obj.GetType();
foreach(var f in t.GetFields()) {
dict[f.Name] = f.GetValue(obj);
}
return dict;
}
Then you can simply do this:
var groupVars = GetObjectFields(NewMainGroup);
foreach(var gv in groupVars) {
Response.Write(<BR>MainGroupName= " + gv.Key + " Value= " + gv.Value.ToString());
var subGroupVars = GetObjectFields(gv.Value);
foreach(var sgv in subGroupVars) {
Response.Write(<BR>SubGroupName= " + sgv.Key + " Value= " + sgv.Value.ToString());
}
}
First thing first GroupA, GroupB and GroupC are not subclasses of MainGroup.
You are using composition and have members which are of GroupA, GroupB and GroupC types.
Not sure why you want to relflect the types when you already know the type you have.
You could have used MainGroup.GroupA.Name and so on. May be the code you posted is just an example?
The below method should reflect the basic structure and suit your purpose.
static String Reflect(Object data)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsClass && propertyInfo.PropertyType != typeof(String))
{
stringBuilder.AppendFormat("{0} : {1} {2}", propertyInfo.Name, Environment.NewLine
, Reflect(propertyInfo.GetValue(data, null)));
}
else
{
stringBuilder.AppendFormat("{0} = {1}, {2}", propertyInfo.Name, propertyInfo.GetValue(data, null), Environment.NewLine);
}
}
return stringBuilder.ToString();
}
usage:
MainGroup main = new MainGroup
{
A = new GroupA { Name = "GroupA", ID = 1 },
B = new GroupB { Date = DateTime.UtcNow },
C = new GroupC { HasData = false }
};
Reflect(main);