Create a CSV of class members from a list<T> - linq

I have a List of a Simple Struct that contains int's and strings.
Struct:
public struct ErrorType
{
public int RowNumber;
public int ColumnNumber;
public string ErrorMessage;
}
On of My methods return A list of these structs.
I want to convert each member in the list to its string form and separate it by a comma so that List is now an Array of strings. I could write a function to do this manually but I'd perfer to use linq to have a cleaner solution.
Having the array of strings I'll write it to a file using
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
List<ErrorType> ErrorTypesList = GetErrors();
//do some work to iterate over the members and do a string.join after
string[] ErrorListArray = ErrorTypesList.foreach( e => { });
File.WriteAllLines(path, createText);
}
does anyone have suggestions on how to fill in the foreach so that it returns each members in its ToString form followed by a comma?

The only way you'd be able to use LINQ for property iteration is if you're using reflection, and you shouldn't do that unless you absolutely have to (which it really doesn't look like you do).
The best you can do, though, still isn't too bad.
var rows = ErrorTypesList
.Select(c => "\"" + string.Join("\",\"", c.RowNumber, c.ColumnNumber, c.ErrorMessage) + "\"");
File.WriteAllLines(path, rows);
I took the liberty of putting fields in quotes as well, you may or may not want that, but it's easy to fix that code to do what you do want. You might also want to add in some escape logic, pending what sorts of contents c.ErrorMessage might have.
You could also use string.Format if you're more comfortable with that, but it doesn't really make a difference here.
var rows = ErrorTypesList
.Select(c => string.Format("\"{0}\", \"{1}\", \"{2}\"", c.RowNumber, c.ColumnNumber, c.ErrorMessage));

It seems you want something like this:
string[] ErrorListArray = ErrorTypesList
.Select(e => string.Join(",", e.RowNumber, e.ColumnNumber, e.ErrorMessage))
.ToArray();

Related

How do I check if a Guid value is inside a LIST of Structures?

How do I check if a Guid value is inside a LIST of Structures?
public struct Info
{
public Guid EntityTypeID;
public String Name;
}
List<Info> InfoList = <function which populates the list of Struct>
...
var values = ctx.EntityValues.Where(v => v.EntityID == e.ID
&& InfoList.Contains(v.EntityTypeItemID)).ToList(); <=== problem here!
//or something like: InfoList[i].EntityTypeID.Contains(v.EntityTypeItemID)).ToList();
Thank you
I suspect you're looking for Any:
... InfoList.Any(x => x.EntityTypeID == v.EntityTypeItemID)
You can't use Contains, because you're looking for something which matches part of the item.
(I'd also strongly discourage using public fields and indeed having mutable structures at all, but that's a different matter.)
Another option would be to create a list of the GUIDs you're interested in:
var guids = InfoList.Select(x => x.EntityTypeID).ToList();
Then you can use:
... guids.Contains(v.EntityTypeItemID)
That may work where the previous code didn't, as it moves the extraction of the type ID out of the main query.

How to extend this LINQ List<>.Contains to work with any Property using Reflection?

I have the following snippet that I currently use to run a .Contains() with a list of Ids passed as a comma separated list from users. This code works perfectly and the data is filtered exactly as I want it to be:
// Handle id in() statements explicitly, dynamic expression can't parse them
var idIn = new Regex("id in ?(.*)", RegexOptions.IgnoreCase);
if (idIn.IsMatch(predicate))
{
Match list = new Regex(#"in ?\((.*)\)", RegexOptions.IgnoreCase).Match(predicate);
string ins = list.Groups[1].ToString();
// Split ins and store as List<>
List<int> splitValues = ins.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(i => Convert.ToInt32(i)).ToList();
return source.Where(u => splitValues.Contains(u.Id));
}
I want to be able to use this same idea, except with ANY property of the u object using reflection. I had a version of this working at some point, but cannot for the life of me figure out what has changed or why it stopped working. Here is the version I have that I cannot get working again:
Match splitIn = new Regex(#"([a-zA-Z0-9\.]*) IN ?\((.*)\)", RegexOptions.IgnoreCase).Match(predicate);
string property = splitIn.Groups[1].ToString();
string ins = splitIn.Groups[2].ToString().Trim(new[] {'\'', '"'}); // Trim off separator quotes
List<string> splitValues = ins.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
for (int i = 0; i < splitValues.Count; i++)
{
splitValues[i] = splitValues[i].Trim(new[] {'\'', '"'});
}
Expression<Func<U, bool>> contains = u => ListContainsProperty(u, splitValues, property);
return source.Where(contains);
private static bool ListContainsProperty<U>(U u, ICollection<string> list, string property)
{
string[] split = property.Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries);
object value = split.Aggregate<string, object>(u, (current, prop) => current.GetType().GetProperty(prop).GetValue(current, null));
return list.Contains(value.ToString());
}
As I said I once had SOME version of this working, but cannot figure out what has changed. Is there something blatantly obvious that I am missing that would help me get this functional again?
Edit: As far as I can tell the ListContainsProperty method is never actually running. Adding a "throw new Exception()" does nothing. I just get the full unfiltered list back.
I think the underlying problem is using "Expression"
you need to compile an Expression.
For example in your code
Expression<Func<U, bool>> contains = u => ListContainsProperty(u, splitValues, property);
is data and not a function. In order to use it you need to compile it.
Func<U, bool> compiled = contains.Compile();
"compiled" variable will call the "ListContainsProperty" method.

Turn this code into LINQ

I have some code that I know could be nicer if it's done in LINQ, but I don't know how the LINQ code would look like.
I have a collection of GoodsItems, in each of this Item there is a Collection of Comments, and some of these comments I want to filter out and turn into a single string line.
Here is the code:
//-- get all comments that is of type "GoodsDescription"
ICollection<FreeText> comments = new List<FreeText>();
foreach (DSV.Services.Shared.CDM.Shared.V2.GoodsItem goodsItem in shipmentInstructionMessage.ShipmentInstruction.ShipmentDetails.GoodsItems)
{
ICollection<DSV.Services.Shared.CDM.Shared.V2.FreeText> freeTexts = goodsItem.Comments.Where(c => c.Type.ToLower() == FREETEXT_TYPE_GOODSDESCRIPTION.ToLower()).ToList();
foreach (DSV.Services.Shared.CDM.Shared.V2.FreeText freeText in freeTexts)
comments.Add(FreeText.CreateFreeTextFromCDMFreeText(freeText));
}
//-- Turn this collection of comments into a single string line
StringBuilder sb = new StringBuilder();
foreach (FreeText comment in comments)
sb.Append(comment.ToString());
contents = sb.ToString();
First Foreach loops thru all goodsitems and for each goods item I get all comments where the Type of the comment is Equale to a defined value.
Then foreach of this comment that I get I create a new Object and add to a CommentsCollection.
And the last thing is that I loop thru this commentsColletion and create all it's data into a single string line.
There must be a nicer and smart way to do this with LINQ.
Thanks...
It looks like you could do this:
var comments = from goodsItem in shipmentInstructionMessage.ShipmentInstruction.ShipmentDetails.GoodsItems
from freeText in goodsItem.Comments.Where(c => string.Equals(c.Type, FREETEXT_TYPE_GOODSDESCRIPTION, StringComparison.InvariantCultureIgnoreCase))
select FreeText.CreateFreeTextFromCDMFreeText(freeText).ToString();
string contents = string.Join("", comments);
It's probably slightly more readable, if only because you've lost most of the types (although you could also have achieved this with implicitly typed local variables).
(I also changed how the string comparison on the comment type is done – I assume you were trying to achieve a case invariant comparison. You may want to use StringComparison.CurrentCultureIgnoreCase instead, depending on what the content of the comments is.)

At least one one object must implement Icomparable

I am attempting to get unique values in a list of similar value distinguished only by a one element in a pipe delimited string... I keep getting at least one object must implement Icomparable. I don't understand why I keep getting that. I am able to groupBy that value... Why can't I find the max... I guess it is looking for something to compare it with. If I get the integer version will it stop yelling at me? This is the last time I am going to try using LINQ...
var queryResults = PatientList.GroupBy(x => x.Value.Split('|')[1]).Select(x => x.Max());
I know I can get the unique values some other way. I am just having a hard time figuring it out. In that List I know that the string with the highest value amongst its similar brethren is the one that I want to add to the list. How can I do that? I am totally drawing a blank because I have been trying to get this to work in linq for the last few days with no luck...
foreach (XmlNode node in nodeList)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(node.OuterXml);
string popPatInfo = xDoc.SelectSingleNode("./template/elements/element[#name=\"FirstName\"]").Attributes["value"].Value + ", " + xDoc.SelectSingleNode("./template/elements/element[#name=\"LastName\"]").Attributes["value"].Value + " | " + DateTime.Parse(xDoc.SelectSingleNode("./template/elements/element[#name=\"DateOfBirth\"]").Attributes["value"].Value.Split('T')[0]).ToString("dd-MMM-yyyy");
string patientInfo = xDoc.SelectSingleNode("./template/elements/element[#name=\"PatientId\"]").Attributes["value"].Value + "|" + xDoc.SelectSingleNode("./template/elements/element[#name=\"PopulationPatientID\"]").Attributes["enc"].Value;// +"|" + xDoc.SelectSingleNode("./template/elements/element[#name=\"AdminDate\"]").Attributes["value"].Value;
int enc = Int32.Parse(patientInfo.Split('|')[1]);
if (enc > temp)
{
lastEncounter.Add(enc, patientInfo);
temp = enc;
}
//lastEncounter.Add(Int32.Parse(patientInfo.Split('|')[1]));
PatientList.Add( new SelectListItem { Text = popPatInfo, Value = patientInfo });
}
I was thinking about using some kind of temp variable to find out what is the highest value and then add that string to the List. I am totally drawing a blank however...
Here I get the IDs in an anonymous type to make it readable.
var patientEncounters= from patient in PatientList
let PatientID=Int32.Parse(patient.Value.Split('|')[0])
let EncounterID=Int32.Parse(patient.Value.Split('|')[1])
select new { PatientID, EncounterID };
Then we group by UserID and get the last encounter
var lastEncounterForEachUser=from pe in patientEncounters
group pe by pe.PatientID into grouped
select new
{
PatientID=grouped.Key,
LastEncounterID=grouped.Max(g=>g.EncounterID)
};
Linq doesn't know how to compare 2 Patient objects, so it can't determine which one is the "greatest". You need to make the Patient class implement IComparable<Patient>, to define how Patient objects are compared.
// Compare objets by Id value
public int CompareTo(Patient other)
{
return this.Id.CompareTo(other.Id);
}
Another option is to use the MaxBy extension method available in Jon Skeet's MoreLinq project:
var queryResults = PatientList.GroupBy(x => x.Value.Split('|')[1])
.Select(x => x.MaxBy(p => p.Id));
EDIT: I assumed there was a Patient class, but reading your code again, I realize it's not the case. PatientList is actually a collection of SelectListItem, so you need to implement IComparable in that class.

Remove duplicates using linq

I know this as asked many times but cannot see something that works.
I am reading a csv file and then I have to remove duplicate lines based on one of the columns "CustomerID".
Basically the CSV file can have multiple lines with the same customerID.
I need to remove the duplicates.
//DOES NOT WORK
var finalCustomerList = csvCustomerList.Distinct().ToList();
I have also tried this extension method //DOES NOT WORK
public static IEnumerable<t> RemoveDuplicates<t>(this IEnumerable<t> items)
{
return new HashSet<t>(items);
}
What works for me is
I Read the CSV file into a csvCustomerList
Loop through csvCustomerList and check if a
customerExists If it doesnt I add
it.
foreach (var csvCustomer in csvCustomerList)
{
var Customer = new customer();
customer.CustomerID = csvCustomer.CustomerID;
customer.Name = csvCustomer.Name;
//etc.....
var exists = finalCustomerList.Exists(x => x.CustomerID == csvCustomer.CustomerID);
if (!exists)
{
finalCustomerList.Add(customer);
}
}
Is there a better way of doing this?
For Distinct to work with non standard equality checks, you need to make your class customer implement IEquatable<T>. In the Equals method, simply compare the customer ids and nothing else.
As an alternative, you can use the overload of Distinct that requires an IEqualityComparer<T> and create a class that implements that interface for customer. Like that, you don't need to change the customer class.
Or you can use Morelinq as suggested by another answer.
For a simple solution, check out Morelinq by Jon Skeet and others.
It has a DistinctBy operator where you can perform a distinct operation by any field. So you could do something like:
var finalCustomerList = csvCustomerList.DistinctBy(c => c.customerID).ToList();

Resources